-1

I am making an API request via PHP cURL.

When I run echo $response I get the following JSON:

JSON (application/json):

{
    "workers": [
        {
            "email": "micky@mcgurk.com",
            "manager": {
                "email": "boss@mcgurk.com"
            }
        },
        {
            "email": "michelle@mcgurk.com",
            "manager": {
                "email": "another_boss@mcgurk.com"
            }
        }
    ]
}

I'd like to loop through the results & echo out the email and associated manager. How do I do this?

michaelmcgurk
  • 6,137
  • 22
  • 81
  • 184

3 Answers3

3

Look into json_decode() http://php.net/manual/en/function.json-decode.php

The result will be an associative array (or object) that you can iterate through

Eriks Klotins
  • 3,804
  • 1
  • 10
  • 24
2

Use PHP's function json_decode()

<?php
$json = '{
    "workers": [
        {
            "email": "micky@mcgurk.com",
            "manager": {
                "email": "boss@mcgurk.com"
            }
        },
        {
            "email": "michelle@mcgurk.com",
            "manager": {
                "email": "another_boss@mcgurk.com"
            }
        }
    ]
}';
$dec = json_decode($json);
$users = array();
if (! empty($dec->workers)) {
    foreach ($dec->workers as $worker) {
        $user['email'] = $worker->email;
        $user['manager_email'] = $worker->manager->email;
        $users[] = $user;
    }
}
echo '<pre>';print_r($users);echo '</pre>';
?>

Output:

Array
(
    [0] => Array
        (
            [email] => micky@mcgurk.com
            [manager_email] => boss@mcgurk.com
        )

    [1] => Array
        (
            [email] => michelle@mcgurk.com
            [manager_email] => another_boss@mcgurk.com
        )

)

Now, loop over $dec->workers and you will get the required email addresses.

Pupil
  • 23,528
  • 5
  • 42
  • 64
1
$data = json_decode($response, true);
Militaru
  • 483
  • 5
  • 9