Renegade Rob Renegade Rob - 7 months ago 21
PHP Question

PHP Specific JSON Array nesting level Confusion

I was wondering if someone could help please. I have a JSON feed from an API, and I can never figure out the levels to get the information I need?

the JSON is below

{
"sourceId": "1234",
"sourceType": "MONITOR",
"searchMeta": {
"startTimestamp": 1462361513,
"endTimestamp": 1462508560,
"maxResults": 10000,
"metricType": [
"clients"
],
"family": [
"Product"
],
"metricsInterval": "M5"
},
"clients": {
"One": [
{
"timestamp": 1462361400,
"avg": 2,
"min": 1,
"max": 3,
"probes": 6,
"samples": 3,
"sources": [
"123",
"234",
"345",
"456",
"567",
"789"
]
},


I was wanting to get the Probes value and the Samples value into a variable

foreach($json['clients'] as $range => $product){

echo $product['timestamp']." Probes: ".$product['probes']." Samples: ".$product['samples']." <br>";

}


Thanks in advance

Answer

I assume you'll have a range of clients (hence the loop). So you'll need to loop each client too as it's an array of object's.

If you visualise it, that looks like this:

CLIENTS = ARRAY(
    1 => ARRAY( OBJECT{} ), // you want the OBJECT{}
    ....etc
)

So the below loop will get it for you.

$data = json_decode($json, TRUE);

foreach($data['clients'] as $range => $product) {
    foreach($product as $element){
        echo $element['timestamp']." Probes: ".$element['probes']." Samples: ".$element['samples']." <br>";    
    }
}

Example/Demo

Returns the following:

1462361400 Probes: 6 Samples: 3 <br>