我有以下的PHP數組:PHP索引數組關聯JSON
array("Apple", "Pear", "Grape", "Orange")
而且我想獲得JSON輸出類似如下:
[[{"fruit":"Apple"}],[{"fruit":"Pear"}],[{"fruit":"Grape"}],[{"fruit":"Orange"}]]
JSON混淆了我:(
編輯 對不起,輸出中的最後兩位應該是水果,我糾正它,對不起。
我有以下的PHP數組:PHP索引數組關聯JSON
array("Apple", "Pear", "Grape", "Orange")
而且我想獲得JSON輸出類似如下:
[[{"fruit":"Apple"}],[{"fruit":"Pear"}],[{"fruit":"Grape"}],[{"fruit":"Orange"}]]
JSON混淆了我:(
編輯 對不起,輸出中的最後兩位應該是水果,我糾正它,對不起。
$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"}]]
OP有兩個「水果」和兩個「標籤」。你只做水果。 –
@馬克:糟糕,我沒注意到。 –
@Marc:OP解決了他的問題,所有的鍵都是「水果」。 –
json_encode是你要找的
如果你想你的JSON輸出的樣子,你應該改變你的PHP值看起來像這樣的功能:
array(array(array('fruit' => 'Apple')), array(array('fruit' => 'Pear')), array(array('fruit' => 'Grape')), array(array('fruit' => 'Orange')))
,然後傳遞數組json_encode()
是的,以及如何將索引PHP數組更改爲關聯PHP數組,所有這些都使用相同的鍵?這是我不知道的。 (array('fruit'=>'Apple')),array(array('fruit'=>'Pear')))' – Pyrite
)要獲得OP要的JSON格式,您的數組應該是'array 。我不確定OP的意思是將索引數組更改爲關聯數組,但都使用相同的鍵。關聯數組的每個鍵的值不能多於一個,除非您創建這些值數組或其他值。 –
固定格式( –
你可以寫人使用索引數組和您想要的鍵值的ittle函數,並吐出所需的結構。
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);
(旁白:選擇比我有更好的功能名稱)
「associativify」+1這個詞 –
我也會+1,但那樣會歪曲事情。 –
你JSON是對象的數組的數組。你確定這就是你想要的? –
你如何確定哪些數組項是'水果',哪個是'標籤'? – salathe
這是$ javascript-> object()在CakePHP中吐出的格式,以及FusionCharts想要的內容。真正的問題是如何將索引PHP數組轉換爲具有所有相同鍵的關聯PHP。 – Pyrite