Reputation: 403
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
Upvotes: 1
Views: 69
Reputation: 9583
The demand of OP:
I was wanting to get the Probes value and the Samples value into a variable
Simple just name your json file as $json
.
$arr = json_decode($json);
echo $samples = $arr->clients->One[0]->samples; //3
echo $probes = $arr->clients->One[0]->probes; //6
Upvotes: 0
Reputation: 13128
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>";
}
}
Returns the following:
1462361400 Probes: 6 Samples: 3 <br>
Upvotes: 1
Reputation: 166
Try this.
$data = json_decode($json,true);
foreach($data['clients'] as $client){
echo $client['timestamp']." Probes: ".$client['probes']." Samples: ".$client['samples']." <br>";
}
Upvotes: 0