Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

access object array in php from json decode

I have this response from json_decode()

// Decode JSON into PHP array
$response_data = json_decode($curl_data, true);

$user_data = $response_data;
var_dump($user_data);

Response :

array(3) { ["Items"]=> array(1) { [0]=> array(3) { ["date"]=> string(9) "4/12/2022" ["ongoing"]=> string(1) "1" ["id"]=> string(1) "1" } } ["Count"]=> int(1) ["ScannedCount"]=> int(1) }

now I just wanted to get the ongoing part so I did it like this

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if(!empty($user_data))
{
  foreach($user_data as $user)
  {
    var_dump($user[0]->ongoing);
  }
}

but it gives me an error

enter image description here

$user_data has the response above. Why is it giving me an error like that

now I have a different error when I tried this

// Decode JSON into PHP array
$response_data = json_decode($curl_data, true);

// Print all data if needed
// print_r($response_data);
// die();

// All user data exists in 'data' object
$user_data = $response_data;

if(!empty($user_data))
{
  foreach($user_data as $user)
  {
    var_dump($user[0]['ongoing']);
  }
}

enter image description here

>Solution :

In your loop your handle your item as object. var_dump($user[0]->ongoing); but you pass to the decode function the second parameter true. Then you return an array. Afterwards you have access like that: $user[0]['ongoing']

Update

The problem is that you have item, count and ScannedCount as key. But only item has the property ongoing. You need a condition to check if the key ongoingexists. Then it works.

$str = '{"Items":[{"date":"4/12/2022","ongoing":"1","id":"1"}],"Count":1,"ScannedCount":1}';
$user_data = json_decode($str, true);

if (! empty($user_data)) {
    foreach($user_data as $key => $value) {
        if ($key === 'Items') {
           print_r($value[0]['ongoing']);   
        }
        
    }   
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading