Jump to content

Recommended Posts

Hello.

 

Last weekend I requested help on how to sort a multidimension array; I was requested to look into array_multisort() but, after reading about this function I'm still not able to get the results I need.

 

I currently have the following array that gets populated in a for loop:

 

$data[$num_records]['cust_id']    = $row["eq_cust_id"];

$data[$num_records]['cust_name']  = $customer_name;

$data[$num_records]['cust_mac']  = $row["eq_mac_address"];

$data[$num_records]['cust_ip']    = $cust_ip;

$num_records++;

 

array_multisort( $data[]['cust_ip'], SORT_NUMERIC);

 

After the loop I would like to be able to sort the array by 'cust_name' or 'cust_ip' but, can't figure out how. Please help.

 

Thanks in advanced.

Link to comment
https://forums.phpfreaks.com/topic/168887-sorting-multidimension-array/
Share on other sites

I wouldn't use array_multisort() for this because you would have to first "transform" the array into a different format (see Example#3). A better option, in my opinion, would be to use usort() to define your own sorting function.

 

function sortByName($a, $b)
{
    return strcasecmp($a['cust_name'], $b['cust_name']);
}

usort($data, "sortByName");
//Records will now be sorted based on name

 

You can also get fancier to sort by two or more columns, i.e. the the primary value is equal then do a secondary (or more) sort on another column.

 

function sortByNameIP($a, $b)
{
    if (strcasecmp($a['cust_name'], $b['cust_name'])==0)
    {
        //If name is same, then sort on ip
        return strcasecmp($a['cust_ip'], $b['cust_ip']);
    }
    return strcasecmp($a['cust_name'], $b['cust_name']);
}

usort($data, "sortByNameIP");
//Records will now be sorted based on name, then IP

 

Note: I have not tested any of this. It may work as expected, not sure. It's late and I'm not in the mood for creating test data. But the idea is sound.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.