我有一个以下的PHP数组:
array("Apple", "Pear", "Grape", "Orange")
我希望获得以下JSON输出:
[[{"fruit":"Apple"}],[{"fruit":"Pear"}],[{"fruit":"Grape"}],[{"fruit":"Orange"}]]
JSON让我很困惑:(
编辑 对不起,输出结果中最后两个应该是水果,我已经更正了,对不起大家。
array(array(array('fruit' => 'Apple')), array(array('fruit' => 'Pear')), array(array('fruit' => 'Grape')), array(array('fruit' => 'Orange')))
然后将该数组传递给json_encode()
array(array(array('fruit' => 'Apple')),array(array('fruit' => 'Pear')))
. - gen_Eric$fruit = array("Apple", "Pear", "Grape", "Orange");
$json = array();
foreach($fruit as $f){
$json[][] = array('fruit' => $f);
}
echo json_encode($json);
// [[{"fruit":"Apple"}],[{"fruit":"Pear"}],[{"fruit":"Grape"}],[{"fruit":"Orange"}]]
function associativify($array, $key) {
$result = array();
foreach ($array as $item) {
$result[] = array(array($key => $item));
}
return $result;
}
$subject = array("Apple", "Pear", "Grape", "Orange");
$munged = associativify($subject, 'fruit');
$json = json_encode($munged);
(顺便说一句:选择一个比我更好的函数名!)
json_encode 是你要找的函数
fruit
和label
。 - gen_Eric