Ali Zia Ali Zia - 13 days ago 7
JSON Question

How can I loop through a JSON Object in PHP?

I have a variable

$arr
in PHP. It has the following data inside it.

This is my PHP Code.

$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

I want to loop through it. How can I achieve it? I tried using foreach but it gives me error. Thanks in advance.

Answer

You have to decode your CURL output string twice:-

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

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

Note:- @Xatenev mentioned the correct thing:-

The json has escaped quotes. When a json with escaped quotes is passed to json_decode() it only removes all the escaped sequences. When calling json_decode() again, it decodes it correctly

Comments