Как перебрать элемент объектов и массив - PullRequest
0 голосов
/ 27 декабря 2018

Я не знаю, как перебрать этот вывод, это может быть просто, но попробовать несколько методов безуспешно.

У меня есть результат запроса, который выбрасывает json с объектами и исправлениями, но я могуне получить значения процессора, памяти и диска:

<?php
// How to read influx data with curl
$query = urlencode("select * from calls limit 1");
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 1); //timeout in seconds
curl_setopt($ch, CURLOPT_URL,"http://127.0.0.1:8086/query?db=myDB&q=$query");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$res =  json_decode(curl_exec ($ch));
curl_close ($ch);
var_dump($res);
?>

, и я получаю этот вывод:

{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}

Попробуйте, например:

foreach ($res as $test) {
     echo $test->statement_id->cpu;
}

Я хочу, чтобы ямог бы получить это:

hostname         time            cpu    mem load    load
linux01   1970-01-01T00:00:00Z    1      78   0       0

Извините за мой плохой английский.

Ответы [ 2 ]

0 голосов
/ 27 декабря 2018

Вам нужно преобразовать его из JSON в объект или массив.

Вот типичная ситуация с массивом:

$results = json_decode('{"results":[{"statement_id":0,"series":[{"name":"custom","tags":{"hostname":"LINUX01"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",1,78,0,0]]},{"name":"custom","tags":{"hostname":"LINUX02"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",6,48,0,0]]},{"name":"custom","tags":{"hostname":"LINUX03"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",5,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX04"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",35,94,0,0]]},{"name":"custom","tags":{"hostname":"LINUX05"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",3,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX06"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",57,25,0,0]]},{"name":"custom","tags":{"hostname":"LINUX07"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,47,0,0]]},{"name":"custom","tags":{"hostname":"LINUX08"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",41,30,0,0]]},{"name":"custom","tags":{"hostname":"ues90078"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",40,20,0,0]]},{"name":"custom","tags":{"hostname":"LINUX09"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,45,0,0]]},{"name":"custom","tags":{"hostname":"LINUX041"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",31,30,0,0]]},{"name":"custom","tags":{"hostname":"LINUX042"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",33,8,0,0]]},{"name":"custom","tags":{"hostname":"LINUX043"},"columns":["time","cpu","mem","load","load"],"values":[["1970-01-01T00:00:00Z",54,10,0,0]]}]}]}', true);

foreach ($results["results"][0]["series"] as $array) {

  echo "<table>";
  echo "<thead>";

  echo "<tr>";
  foreach ($array["columns"] as $value) {
    echo "<th>{$value}</th>";
  }
  echo "</tr>";

  echo "</thead>";
  echo "<tbody>";

  echo "<tr>";
  foreach ($array["values"][0] as $value) {
    echo "<td>{$value}</td>";
  }
  echo "</tr>";

  echo "</tbody>";
  echo "<table>";

}

Если вы хотите что-то конкретное:

foreach ($results["results"][0]["series"] as $array) {

  foreach ($array["columns"] as $key => $value) {
    if ($value === "cpu") $column = $key;
  }

  echo "cpu: {$array["values"][0][$column]}.<br>";

}

Чтобы добавить имя хоста, просто добавьте:

echo "<tr>";
echo "<th colspan=" . count($array["columns"]) . ">{$array["tags"]["hostname"]}</th>";
echo "</tr>";

после echo "<thead>";.

0 голосов
/ 27 декабря 2018

Вам будет трудно работать с этими данными как есть, потому что большая часть данных не имеет ключей, и это вводит в заблуждение при работе с объектом.В этом случае было бы легче, если бы вы работали с массивом.Вы можете сделать это, используя true в качестве второго параметра декодирования.

$data =  json_decode(curl_exec ($ch), true);

$results = $data['results'];

foreach ($results['series'] as $server) {
    $cpuIndex = array_search('cpu', $server['columns']);
    echo $server['values'][$cpuIndex];
}
...