Here is my php code with json formatted string:
<?php
$string='{"items": [
{
"address":"W 7th Ave"
},
{
"address":"W 8th St"
}
]}';
$json = json_decode($string, true);
foreach ($json as $key => $value){
echo "$key: $value\n";
};
?>
I want to learn how to parse/output json string into something I can show in html or put into database .. however i am stuck on something that is prob very simple but I've spent most of the morning trying to figure out.
What I want to understand is why the results of my code above gives me the following result:
"items: Array"
And not what I want/expect to get:
"items: W 7th Ave"
"items: W 8th St"
What am i missing? Isn't "Address" the next "level" down from "Item" in the array?
Your items are in an array. You could loop through them like this:
foreach ($json['items'] as $address)
{
echo 'Address: '.$address;
}
$string = file_get_contents('./string.json');
$json = json_decode($string);
if you want to have items: <address>
:
foreach ($json['items'] as $address)
{
echo "items:". $address['address'] ."\n";
};
anyway if you are not sure about how an array is built you could print it via:
print_r($json);
which will print:
Array
(
[items] => Array
(
[0] => Array
(
[address] => W 7th Ave
)
[1] => Array
(
[address] => W 8th St
)
)
)
now you found out that $json
contains just an array (items
) of two array, then, if you loop it, you will get that array which is printed in your example.
As explained above you need to go one step deeper by looping the elements in your items
array and print their address
element.
here is the complete script: http://pastie.org/2275879
BTW, I did do var_dump, print, print_r, switch it back and forth from Object to Array, to try to learn more about array structure etc and also did a bunch of variations of echo, and for and foreach loops, etc to try to get what i wanted from array.
Ok so to summarize, the answers seem to indicate i have to:
I tried both answers and got:
Using TaylorOtwell answer:
I got: Address: Array Address: Array
Taylor
Using Dalen's answer:
I got: 0: Array 1: Array
Looks like i need to somehow loop through array a second time within the first foreach to get actual values?
Would it look something like this?
foreach ($json['items'] as $key => $value)
{
foreach ($json['items']['address'] as $key => $value)
{
echo "$key: $value\n";
};
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With