loop through array in php

Question:

I would like to iterate through an array but I only want a single field which in this case would be "status". Let it print the word open on the screen. Please help!

This is the fix:

{
    "status": "Abierto",
    "last_author": "56935387022"
}

This is my code:

$ch = curl_init();

$options = array(CURLOPT_URL => 'https://api-cluster.postcenter.io/v2/ticket/5d9b5a86b2a7d10db4a05935/',
                 CURLOPT_HEADER => false,
                 CURLOPT_RETURNTRANSFER=> TRUE,
                 CURLOPT_HTTPHEADER => array(
                    'Authorization: Key 76e7e6402ed09e3def8e09eaba1d94ea46985e4b24c6a3a422b42c06aabb1f232d6e9beb814531d233abc2564393330606e68be35987470e60a746adbe9bb117',
                    "cache-control: no-cache"
                )
                );

curl_setopt_array($ch, $options);

$r=curl_exec($ch);

    if(!$r)
    {
        $mData=array( curl_error($ch) );

    } else {
        $json=json_decode($r);
        $mData=$json;
    }

    curl_close($ch);


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

Answer:

I think you have a confusion between what is a JSON object and a JSON array.

This is a JSON object:

{
    "status": "Abierto",
    "last_author": "56935387022"
}

It is not a fix. If it were an array it would start with [ and end with ] . This is an important difference to understand when working with JSON responses that come from cURL or from APIs or otherwise.

Consequently, you can read the data directly, like so: $json->status .

Let's see a test:

$r=
    '
{
    "status": "Abierto",
    "last_author": "56935387022"
}
    ';
$json=json_decode($r);
echo $json->status;

Exit:

Abierto

Let's look at an example of a JSON array (notice how it starts and how it ends).

$r=
    '
    [
{
    "status": "Abierto",
    "last_author": "56935387022"
},
{
    "status": "Cerrado",
    "last_author": "56935387023"
}
    ]
    ';
$json=json_decode($r);

Here you can read into a loop, regardless of whether it's an array of objects:

foreach ($json as $item){
    echo $item->status.PHP_EOL;
}

Exit:

Abierto
Cerrado

Or you can access directly using the index:

echo $json[0]->status;

Exit:

Abierto
Scroll to Top