genoki
genoki

Reputation: 131

php json_decode how to output array

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?

Upvotes: 13

Views: 92094

Answers (5)

Mehul S
Mehul S

Reputation: 1

First create a class for your elements.

function getAddress(address)
{
this.address=address;
}

Push objects to your array

newAddress = JSON.stringify(new 
getAddress(address));
AddressArray.push(newAddress);

Convert your array as JSON Array using

AllAddress=JSON.stringify(AddressArray);

Send your array to backend/fetch elements like

$json_array  = json_decode($AllAddress, true);
for($i=0;$i<count($json_array);$i++)
{
$eachAddress = json_decode($json_array[$i],true);
$address= $eachAddress["address"];//fetch particular element from your JSON Object
}

*Use implode(php) to get all elements from the array at once.

Upvotes: 0

Dimi
Dimi

Reputation: 269

You might want to simplify your input string as follows

$string='{"address":["W 7th Ave","W 8th St"]}';

$json = json_decode($string, true);
echo'<pre>';
print_r($json);
echo'</pre>';
foreach ($json['address'] as $key=>$value){
echo "Address $key:". $value ."<br>";
};

Upvotes: -1

Dalen
Dalen

Reputation: 8996

$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

Upvotes: 15

curtisp
curtisp

Reputation: 2325

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:

  • first get the whole array eg $string (did that)
  • then decode array into $json (did that)
  • then somehow parse out the sub arrays from $json (by doing something like referencing the addresses in array like "items.address" or "[items][address]" etc (i still am not sure from the answers above how to do this .. they hint at it but can't see syntax etc?)

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";
};
};

Upvotes: 1

TaylorOtwell
TaylorOtwell

Reputation: 7337

Your items are in an array. You could loop through them like this:

foreach ($json['items'] as $address)
{
    echo 'Address: '.$address;
}

Upvotes: 2

Related Questions