将数组推入多维数组?

时间:2012-04-24 22:08:06

标签: php json multidimensional-array

我有json_encoded数组,我想添加到使用PHP

[{"id":"a","value":"2"},{"id":"b","value":"2"}]

我想将以下内容添加到上面的数组中:

array("id" => c, "value" => "3") 

我尝试了json_decode然后尝试将数组推入该数组但我对如何做到这一点感到困惑

1 个答案:

答案 0 :(得分:1)

确保在阵列模式而不是对象模式下使用json_decode

// Default: JSON is decoded as object
$json_object = json_decode($json_string);

// Pass true in the second argument to get an array instead
$json_array = json_decode($json_string, true);

// Push a new entry onto the end
$json_array[] = array("id" => c, "value" => "3");

// Re-encode JSON string, if needed
$json_final_string = json_encode($json_array);