PHP json_decode返回数组和数字键

时间:2016-04-03 09:39:35

标签: php arrays json

我有以下JSON数组:

[
  {"r1t7pjT4wn":{"Title":"test","Meta":"test","SM_D":"test","BIG_D":"test"}},
  {"3rMlBu6LpZ":{"Title":"test1","Meta":"test1","SM_D":"test1","BIG_D":"test1"}}
]

当我json_decode时,我希望看到:

Array ( 
  "r1t7pjT4wn" => Array ( [Title] => test [Meta] => test [SM_D] => test [BIG_D] => test ),
  "3rMlBu6LpZ" => Array ( [Title] => test1 [Meta] => test1 [SM_D] => test1 [BIG_D] => test1 )
)

然而,PHP产生:

Array ( 
  [0] => Array ( [r1t7pjT4wn] => Array ( [Title] => test [Meta] => test [SM_D] => test [BIG_D] => test ) ) 
  [1] => Array ( [3rMlBu6LpZ] => Array ( [Title] => test1 [Meta] => test1 [SM_D] => test1 [BIG_D] => test1 ) ) 
)

2 个答案:

答案 0 :(得分:3)

如果您无法更改源json,请添加一个函数调用

call_user_func_array('array_merge', json_decode($json, true));

答案 1 :(得分:2)

这是因为您的数据 数组!如果它是关联数组(,如果它以{开头并以}结尾),则json_decode将具有输出你期待。

将您的JSON更改为:

{
   "r1t7pjT4wn":{"Title":"test","Meta":"test","SM_D":"test","BIG_D":"test"},
   "3rMlBu6LpZ":{"Title":"test1","Meta":"test1","SM_D":"test1","BIG_D":"test1"}
}