簡體   English   中英

PHP索引數組到關聯JSON

[英]PHP Indexed Array to Associative JSON

我有以下PHP數組:

array("Apple", "Pear", "Grape", "Orange")

我想獲得如下的JSON輸出:

[[{"fruit":"Apple"}],[{"fruit":"Pear"}],[{"fruit":"Grape"}],[{"fruit":"Orange"}]]

JSON讓我困惑:(

編輯對不起,輸出中的最后兩個應該是水果,我糾正了,對不起伙計們。

如果您希望JSON輸出看起來像這樣,您應該將PHP值更改為如下所示:

array(array(array('fruit' => 'Apple')), array(array('fruit' => 'Pear')), array(array('fruit' => 'Grape')), array(array('fruit' => 'Orange')))

然后將該數組傳遞給json_encode()

$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是您正在尋找的功能

http://php.net/json_encode (如果你很懶)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM