我有这样的代码来从API中获取JSON数据:
try {
// connect to Zabbix-API
$api = new ZabbixApi($api_url, $username, $password);
$params = array(
'groupids' => '2',
'real_items' =>TRUE,
'monitored_items' =>TRUE,
'search' => array('name' => 'Disk root used p'),
'selectFunctions' => 'extend',
'output' => 'extend',
'sortfield' => 'name'
);
$trends = $api->itemGet($params); // get data from api
$names = array();
foreach($trends as $trend) { // loop through the returned data
$names[] = $trend->lastvalue;
}
} catch(Exception $e) {
// Exception in ZabbixApi catched
echo $e->getMessage();
}答复是:
"result": [
{
"itemid": "23298",
"hostid": "10084",
"lastvalue": "2552",
"name": "Disk root used p"
},如您所见,我创建了一个数组($names),其中只包含"lastvalue“。现在我试着用"hostid“对这些值进行排序。这有可能吗?怎么可能?
发布于 2015-11-12 15:32:10
首先,您必须对$trends进行排序,然后您可以创建$names,您可以使用usort函数来完成这个任务。它需要一个数组和要用于排序的函数的名称。例如
function sort_trends_by_hostid($a, $b) {
if ( $a->hostid == $b->hostid ) {
return 0;
}
return ($a->hostid < $b->hostid) ? -1 : 1;
}
usort($trends, 'sort_trends_by_hostid');发布于 2015-11-12 15:25:37
您需要php函数"asort":
http://php.net/manual/en/function.asort.php
它对数组进行排序,维护索引关联。
如果您不为维护索引关联而烦恼,请使用sort():
http://php.net/manual/en/function.sort.php
https://stackoverflow.com/questions/33674790
复制相似问题