简体   繁体   中英

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

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>

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

Try this.

$data = json_decode($json,true);
foreach($data['clients'] as $client){

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM