如何在PHP中循环JSON对象?

时间:2016-11-21 08:08:00

标签: php json

我在PHP中有一个变量$arr。它里面有以下数据。

这是我的PHP代码。

    $data = array(
        'Request' => 'StockStatus',
        'merchant_id' => 'shipm8',
        'hash' => '09335f393d4155d9334ed61385712999'
        );

    $url = 'https://ship2you.com/ship2you/';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_PORT, 443);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($ch);
    curl_close($ch);

    $arr = json_decode($result, true);

    foreach ($arr as $value) {
        echo $value['packagename'];
    }

enter image description here

我想循环播放它。我怎样才能实现它?我尝试使用foreach但它给了我错误。提前谢谢。

3 个答案:

答案 0 :(得分:1)

您必须解密CURL output string两次: -

$arr = json_decode(json_decode($result, true),true);

foreach ($arr as $value) {
    echo "<pre/>";print_r($value['packagename']);
}

注意: - @Xatenev提到正确的事情: -

json已经逃脱了引用。当带有转义引号的json传递给json_decode()时,它只会删除所有转义序列。再次致电json_decode()时,它会正确解码

答案 1 :(得分:0)

json_decode($json, true);

如果第二个参数为true,则返回数组。如果它不是您想要的,请显示您的代码。

答案 2 :(得分:0)

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_PORT, 443);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);

$arr = json_decode($result);



foreach ($arr as $arr_item) {
   echo $arr_item->user_id;
}