开发者

PHP Indexed Array to Associative JSON

I have the following PHP array:

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

And I'd like to get JSON out开发者_如何学编程put like the following:

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

JSON confuses me :(

EDIT Sorry, those last two in the output should have been fruit, I corrected it, sorry guys.


If you want your JSON output to look like that, you should change your PHP value to look like this:

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

and then pass that array to 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"}]]


You could write a little function which takes the index array and your desired key value, and spits out the required structure.

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);

(Aside: choose a better function name than I have!)


json_encode is the function you're looking for


http://php.net/json_encode (if you're lazy)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜