Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Indexed Array to Associative JSON

Tags:

json

php

I have the following PHP array:

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

And I'd like to get JSON output 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.

like image 857
Pyrite Avatar asked Jun 24 '26 00:06

Pyrite


1 Answers

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

like image 164
Adam Fabicki Avatar answered Jun 25 '26 18:06

Adam Fabicki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!