0

I have the following JSON on a page

{   
"users": [
        {
            "name": "John",
            "age": "30",
        },
        {
            "name": "Dave",
            "age": "20",
        },
         ...
      ]
    }

I'm decoding it using $json = json_decode($data);. If I want a loop that print every name and age for each user how can I do that?

I'm tring to do something like the following code but it's not working

foreach($json->users->name as $key => $result){
        $name = $result;
        $age = $result->age;

        echo $name;
        echo $age;
        echo "<br>";
}

What am I doing wrong? How could I achieve that?

2
  • print_r($json->users) What do you see? Commented Dec 19, 2016 at 14:18
  • Trying to get property of non-object in <file> on line 44 Commented Dec 19, 2016 at 14:19

2 Answers 2

1

You can do it like this:

$string = "{\"users\": [{\"name\": \"BA8842_530\",\"age\": \"0.0\"},{\"name\": \"BA8842_540\",\"age\": \"20\"}]}";
$json = json_decode($string, true);
foreach ($json['users'] as $key => $value) {
    echo "Name: " . $value['name'] . "<br>";
    echo "Age: " . $value['age'] . "<br>";
}

The output would be:

// Output
Name: BA8842_530
Age: 0.0
Name: BA8842_540
Age: 20
...

Hope this helps!

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

4 Comments

Worked! Thanks a lot, was going crazy hahah
@L.K. - If you find this answer correct and helpful then accept & upvote this answer as it motivates me to give answers to other questions like this and helps others to quickly find the correct answer!
Was waiting 5 minutes to do so ;)
Glad to know, that it helped you. Thanks! :D
1
foreach($json->users as $row){
        echo $row->name;
        echo $row->age;
        echo "<br>";
}

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.