php中的Json数组对象

时间:2011-11-08 08:54:39

标签: php arrays json arraylist

这是我的代码生成的json

{
"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);
?>

但我希望有这样的结构

{
"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代码。

谢谢,

1 个答案:

答案 0 :(得分:3)

  • 取“json-encoded”字符串并将其传递给json_decode()
  • 将返回值分配给变量
  • 将该变量传递给var_export()以获取数据的“php编码”字符串表示形式。

e.g。

<?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',
    ),
  ),
)