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
if(!empty($user_data))
{
foreach($user_data as $user)
{
var_dump($user[0]->ongoing);
}
}
but it gives me an error
$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']);
}
}
>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']);
}
}
}

