如何使用json_encode在外部数组中创建php嵌套数组json对象的内容

时间:2018-04-07 22:55:52

标签: php json associative-array

我有一个数组:

$myAssocArray = array(
           ['fred','tyson',23],
           ['collins', 'white', 54],
           ['mary', 'frost', 46]
        );

当我json_encode数组时:

$jsonString = json_encode($myAssocArray);
echo $jsonString;

我明白了:

[['fred','tyson',23],['collins', 'white', 54],['mary', 'frost', 46]]

但我希望得到以下结果:

[{0:'fred',1:'tyson',2: 23},{0:'collins', 1:'white', 2: 54},{0:'mary', 1:'frost',2: 46}]

2 个答案:

答案 0 :(得分:0)

找到一个解决方案,我不得不将嵌套数组转换为对象

(object) $myDynamicNestedArray;

PHP json_encode - JSON_FORCE_OBJECT mixed object and array output

答案 1 :(得分:0)

array转换为object (object)$array,例如:

function _json_encode($arr){
   return json_encode((object)$arr); 
}

$jsonString = _json_encode($myAssocArray);
print_r($jsonString);