我有这种阵列:
array {
[0] => {"ID":"343","name":"John","money":"3000"}
[1] => {"ID":"344","name":"Erik","money":"2000"}
[2] => {"ID":"346","name":"Ronny","money":"3300"}
}
我想通过JSON将它从PHP读到JavaScript。如您所见,内部数组已按如下方式编码:
json_encode($a)
要从我的JavaScript代码中读取,我希望它使用以下语法:
"[0]" : "{"ID":"343","name":"John","money":"3000"}",
"[1]" : "{"ID":"344","name":"Eric","money":"2000"}",
"[2]" : "{"ID":"345","name":"Ronny","money":"3300"}",
我该怎么做?
答案 0 :(得分:3)
在标题中,您要求如何使用JSON多维数组进行编码。我将假设这是你真正的问题,因为你的问题机构会提出不同的问题。假设您有一个数组$arr
,请不要在每个内部数组json_encode()
上调用$a
。
相反,只需调用json_encode($arr)
,它将编码整个数组,包括内部数组。
$arr = array (
array ("ID" => "343", "name" => "John", "money" => "3000"),
array ("ID" => "344", "name" => "Erik", "money" => "2000"),
array ("ID" => "346", "name" => "Ronny", "money" => "3300")
);
$j = json_encode($arr);
$j
将是这样的:
[{"ID":"343","name":"John","money":"3000"},
{"ID":"344","name":"Erik","money":"2000"},
{"ID":"346","name":"Ronny","money":"3300"}]
您可以使用jQuery.parseJSON()
轻松解析此问题。然后,您可以简单地遍历解析后的数组,从内部数组中获取所需内容。
var arr = jQuery.parseJSON('[{"ID":"343","name":"John","money":"3000"},{"ID":"344","name":"Erik","money":"2000"},{"ID":"346","name":"Ronny","money":"3300"}]');
for(var i = 0; i < arr.length; i++) {
var a = arr[i]; // Inner array.
console.log(a.ID);
console.log(a.name);
console.log(a.money);
}
答案 1 :(得分:2)
$arr = array(
'[0]' => '{"ID":"343","name":"John","money":"3000"}',
'[1]' => '{"ID":"344","name":"Erik","money":"2000"}',
'[2]' => '{"ID":"346","name":"Ronny","money":"3300"}'
);
echo json_encode($arr);