0

I been looking thru the posts here all day but can't figure out what I'm doing wrong. (I'm new to php and json)

Here is my code that work.

    $json = '{"id":1234,"img":"1.jpg"}';
    $data = json_decode($json, true);
    echo $data["img"];

But when the json respond is this

    $json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';

it's a big harder for me. then img is a child of demo1? How to get it?

Thx. :)

2 Answers 2

3

Figuring out the array indices

As you're new to PHP, I'll explain how to figure out the array indces of the required array value. In PHP, there are many functions for debugging — print_r() and var_dump() are two of them. print_r() gives us a human-readable output of the supplied array, and var_dump() gives us a structured output along with the variable types and values.

In this case, print_r() should suffice:

$json = '{"demo1":[{"id":1234,"img":"1.jpg"}],"userId":1}';
$data = json_decode($json, true);

// wrap the output in <pre> tags to get a prettier output

echo '<pre>';
print_r($data);
echo '</pre>';

This will produce the following output:

Array
(
    [demo1] => Array
        (
            [0] => Array
                (
                    [id] => 1234
                    [img] => 1.jpg
                )

        )

    [userId] => 1
)

From there, it should be pretty easy for you to figure out how to access the required vaule.

$data['demo1'][0]['img'];

Creating a helper function for ease of use

For ease of use, you can create a helper function to make this process easier. Whenever you want to view the contents of an array, you can simply call dump_array($array); and be done with it. No more messing around with <pre> tags or print_r().

Function code:

function dump_array($array) {
    echo '<pre>' . print_r($array, TRUE) . '</pre>';
}

Usage example:

$arr = ['foo' => range('a','i'), 'bar' => range(1,9)];
dump_array($arr);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you Amal. Was allmost to easy. Work perfect. :)
@Bulfen: Glad I could help. I've updated the answer to include some more details. Hope that helps. Cheers!
If you are building a debug function, you might as well test if it's an object, and if so, retrieve class name, and methods.
@Loïc: That was not the point. I've updated my answer to to be more clear.
1

after decoding :

echo $data->demo[0]->img;

Basically, a { in JSON leads to a -> (it's an object). And a [ to a [], it's an array.

Comments

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.