使用PHP循环JSON响应

时间:2018-06-18 09:30:10

标签: php json

我正在通过 PHP cURL 发出API请求。

当我运行echo $response时,我得到以下JSON:

JSON(application / json):

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

我想循环播放结果&回应电子邮件和相关经理。我该怎么做?

3 个答案:

答案 0 :(得分:3)

查看json_decode()http://php.net/manual/en/function.json-decode.php

结果将是一个可以迭代的关联数组(或对象)

答案 1 :(得分:1)

$data = json_decode($response, true);

答案 2 :(得分:1)

使用PHP的函数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>';
?>

输出:

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

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

)

现在,循环遍历$dec->workers,您将获得所需的电子邮件地址。