I have simple php code:
<?php
$json = '
{
"TrackResponse": {
"Shipment": {
"Package": {
"TrackingNumber": "1Z7V015Y6870100000",
"Activity": {
"ActivityLocation": {
"Address": {
"City": "Caledon",
"StateProvinceCode": "ON",
"CountryCode": "CA"
}
},
"Status": {
"Type": "I",
"Description": "Departed from Facility",
"Code": "DP"
},
"Date": "20230322",
"Time": "003100"
},
"Activity2": [
{
"ActivityLocation": {
"Address": {
"City": "Caledon",
"StateProvinceCode": "ON",
"CountryCode": "CA"
}
},
"Status": {
"Type": "I",
"Description": "Departed from Facility",
"Code": "DP"
},
"Date": "20230322",
"Time": "003100"
},
{
"ActivityLocation": {
"Address": {
"City": "Caledon",
"StateProvinceCode": "ON",
"CountryCode": "CA"
}
},
"Status": {
"Type": "I",
"Description": "Arrived at Facility",
"Code": "AR"
},
"Date": "20230321",
"Time": "115000"
},
{
"ActivityLocation": {
"Address": {
"City": "Windsor",
"StateProvinceCode": "ON",
"CountryCode": "CA"
}
},
"Status": {
"Type": "I",
"Description": "Departed from Facility",
"Code": "DP"
},
"Date": "20230320",
"Time": "180900"
}
]
}
}
}
}
';
$data = json_decode($json, true);
$activity = $data['TrackResponse']['Shipment']['Package']['Activity'];
$activity2 = $data['TrackResponse']['Shipment']['Package']['Activity2'];
if (is_object($activity)) {
print_r(' Activity is an object ');
} else {
print_r(' Activity is NOT an object ');
}
if (is_array($activity)) {
print_r(' Activity is an array ');
} else {
print_r(' Activity is NOT an array ');
}
if (is_object($activity2)) {
print_r(' Activity2 is an object ');
} else {
print_r(' Activity2 is NOT an object ');
}
if (is_array($activity2)) {
print_r(' Activity2 is an array ');
} else {
print_r(' Activity2 is NOT an array ');
}
?>
Activity could be single object like "Activity" in json or could be array of objects like "Activity2" and I need to indicate if Activity is an array or it’s single object. I try to use is_array function, but it always returns true, despite it’s single object. count($activity) for returns 4 (wrong), count for ($activity2) = 3, correct. How to indicate whether $activity is an array of objects or it’s single object?
>Solution :
Currently you’re decoding the JSON into a set of associative arrays, which means that is_array will always return true when used on any of the items in your decoded data, regardless of what the original JSON contained.
Decode it in the default format, and JSON objects will be turned into objects, while arrays will be turned into arrays. Then your tests will work as expected:
$data = json_decode($json);
$activity = $data->TrackResponse->Shipment->Package->Activity;
$activity2 = $data->TrackResponse->Shipment->Package->Activity2;
Working demo: https://3v4l.org/ljkLc
Background reading: https://www.php.net/manual/en/function.json-decode.php