1

I have this Code to get JSON data from the API:

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();
}

The response is:

"result": [
        {
            "itemid": "23298",
            "hostid": "10084",
            "lastvalue": "2552",
            "name": "Disk root used p"        
        },

As you can see I made an array ($names) with only the "lastvalue" in it. Now I'm trying to sort these values by the "hostid". Is this possible and how?

rand0rn
  • 678
  • 2
  • 12
  • 29
julien
  • 624
  • 1
  • 8
  • 17
  • It looks like the parameters you send to the api allow you to choose the sort field. Why don't you simply specify a sort by `lastvalue` when calling the API such that the API returns results in order the you desire without any additional sorting required in your code? – Mike Brant Nov 12 '15 at 15:48

2 Answers2

3

First you have to sort $trends and then you can create the $names You can do that by using the usort function. It takes an array and the Name of a Function you want to use to do the sorting. For example

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');

Source David Walsh

Alex Paliarush
  • 337
  • 4
  • 6
MadClown
  • 124
  • 7
0

You want the php function "asort":

http://php.net/manual/en/function.asort.php

it sorts the array, maintaining the index associations.

if you're not fussed about preserving index associations, use sort():

http://php.net/manual/en/function.sort.php

Jah
  • 986
  • 5
  • 26