遍历json数组有多个结果

时间:2019-02-26 05:12:54

标签: php json curl

我试图弄清楚如何解析具有多个结果的json响应。这是响应数据-

 Array
 (
    [id] => 7181676
    [api_request_id] => 20984853
    [user] => 8305
    [vin] => JTDKN3DU7D1643423
    [make] => Toyota
    [model_name] => Prius
    [model_year] => 2013
    [last_updated] => 2019-02-22T01:08:15.628318Z
    [recall_count] => 2
    [status] => ok
    [recalls] => Array
        (
            [0] => Array
                (
                    [recall_id] => 15753
                    [recall_age] => 0
                    [nhtsa_id] => 18V684000

                )
            [1] => Array
                (
                    [recall_id] => 16733
                    [recall_age] => 1
                    [nhtsa_id] => 16V684123

                )
        )
)

我想循环遍历以获取召回[0]和召回[1],因为我不知道会有多少结果,因此无法手动完成。

我正在寻找的答复是-

2013 Toyota Prius

Recall ID - 1573
Recall Age - 0
Nhtsa Id - 18v684000

Recall ID - 16733
Recall Age - 1
Nhtsa Id - 16v684123

我会做这样的事情吗? -

$data = curl_exec($ch);
$responseData = json_decode($data, TRUE);

foreach($responseData as $item){
    echo $item;
}

2 个答案:

答案 0 :(得分:2)

您可以循环遍历数据中的recalls数组;通过使用foreach循环,您不必担心数组中有多少:

foreach ($responseData['recalls'] as $key => $recall) {
    echo "recall $key:\n";
    echo "recall id: {$recall['recall_id']}\n";
    echo "recall age: {$recall['recall_age']}\n";
    echo "nhtsa id: {$recall['nhtsa_id']}\n\n";
}

输出:

recall 0: 
recall id: 15753
recall age: 0 
nhtsa id: 18V684000 

recall 1: 
recall id: 16733
recall age: 1 
nhtsa id: 16V684123

Demo on 3v4l.org

答案 1 :(得分:1)

通过for循环遍历数组 例如:

for ($i = 0; $i < count($responseData['recalls']); $i++) {
    $result = $responseData['recalls'][$i];
    echo $result['recall_id'].'<br>';
    echo $result['recall_age'].'<br>';
    echo $result['nhtsa_id'].'<br>';
}