13

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?

1
  • In foreach part, $json returns array. Commented Jul 26, 2011 at 17:03

5 Answers 5

15
$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

Sign up to request clarification or add additional context in comments.

2 Comments

unfortunately for me print_r just prints everything as one long string of text :(
@johnktejik depending on your situation, the <pre> HTML tag might help you preserve the helpful whitespace coming from print_r()
2

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

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

Comments

1

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

5 Comments

ok i think i get the point, i've updated my two foreach statement try to test them, they will let you use just one foreach instead of two
Ah, success. The syntax i was missing was $address['address'] .. thanks! my json string is actually 190 addresses in the items array. I have it in a separate file that i would like to refer to directly in $string but it doesn't get picked up by $string='./items.json'; which does work for some json strings i have tried. i can copy & paste the entire string into the php file as $string which does work fine. What syntax would i use to refer to remote json file?
i've edited my answer again, check the first two lines of code
More success .. file_get_contents('./string.json'); was what i needed ... i had tried another method that used a var "MyUrl" = file name in the following $.getJSON(MyUrl, function(items) .. so i thought i could just use url as $string in $json .. but now see that .getjson is pretty obviously "get" and $string isn't so needs something to "get" like file_get_contents. cheers
$.getJSONis a jquery function wich is javascript, totally another language. If my answer solved your problem then you should accept it! bye
0

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.

Comments

-1

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

1 Comment

this doesn't solve the op's problem of parsing the json he showed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.