php中的Json对象数组 [英] Json array of objects in php

查看:31
本文介绍了php中的Json对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码生成的json

this is the json that my code produces

{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555}
}

这是代码

<?php
$c = array('a' => 11111, 'b' => 222222, 'c' => 33333, 'd' => 444454, 'e' => 55555555 );
$arr = array('aaa' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5 , 'fff'=>$c);
echo json_encode($arr);
?>

但我想要一些这样的结构

but I want to have some structure like this

{
"aaa":1,
"b":2,
"c":3,
"d":4,
"e":5,
"fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
"last":[
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501,
        "loc": "NEW YORK STATE"
      }
    ]
}

我是 json 和 php 的新手,我需要这么快,所以我没有时间阅读这个 json 结构......所以如果有人知道如何添加最后一个元素,请提供一些 php 代码.

I am new in json and php and I need this fast so I do not have time to read about this json structure... So please if someone know how to add this last element please provide some php code.

谢谢,

推荐答案

  • 获取json-encoded"字符串并将其传递给 json_decode()
  • 将返回值赋给变量
  • 将该变量传递给 var_export() 以获得数据的php 编码"字符串表示.
  • 例如

    <?php
    $json = '{
    "aaa":1,
    "b":2,
    "c":3,
    "d":4,
    "e":5,
    "fff":{"a":11111,"b":222222,"c":33333,"d":444454,"e":55555555},
    "last":[
          {
            "id": 8817,
            "loc": "NEW YORK CITY"
          },
          {
            "id": 2873,
            "loc": "UNITED STATES"
          },
          {
            "id": 1501,
            "loc": "NEW YORK STATE"
          }
        ]
    }';
    
    
    $php = json_decode($json, true);
    echo var_export($php);
    

    印刷品

    array (
      'aaa' => 1,
      'b' => 2,
      'c' => 3,
      'd' => 4,
      'e' => 5,
      'fff' => 
      array (
        'a' => 11111,
        'b' => 222222,
        'c' => 33333,
        'd' => 444454,
        'e' => 55555555,
      ),
      'last' => 
      array (
        0 => 
        array (
          'id' => 8817,
          'loc' => 'NEW YORK CITY',
        ),
        1 => 
        array (
          'id' => 2873,
          'loc' => 'UNITED STATES',
        ),
        2 => 
        array (
          'id' => 1501,
          'loc' => 'NEW YORK STATE',
        ),
      ),
    )
    

    这篇关于php中的Json对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆