Portal Home > Knowledgebase > Articles Database > Sorting array in specific way


Sorting array in specific way




Posted by HoratioE, 02-08-2013, 06:27 AM
Hello, I'm looking for a way to sort array elements in a multilevel array: $status_array[hosts][host] by their respective sub-item values: $status_array[hosts][host][n][host_name]. Anyone know where I should be looking? Thank you

Posted by TwineDev, 02-08-2013, 04:17 PM
Here is what I have done in the past, and works good for arrays that are not huge. Adjust the levels of the array for your own needs. Note, if you need to sort by more than one key, just stack them (see second example in the code), but be sure for numbers to left pad them to the max that you think they would be, so that they sort properly ( so 1400 doesn't come before 90, you need to pad: 001400 000090 ) Also note when building the $index, we are adding a ~# to the end so that every key will be unique. Output:

Posted by luki, 02-08-2013, 06:04 PM
Look at usort or uasort and define your own callback function that will be used to compare two elements and define their relative order.

Posted by TwineDev, 02-08-2013, 10:03 PM
Thanks Luki, you know I had never really looked at using those functions much. I came up with the following to give the same output as the other example I first gave. Much easier, plus now the original array is actually sorted. My way earlier the original data was not changed.

Posted by mobilespecialists, 02-09-2013, 05:06 AM
usort link http://www.php.net/manual/en/function.usort.php



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
HB9.NET Gone???? (Views: 861)
Burst/Nocster Down (Views: 643)
QuickPacket.Com (Views: 637)

Language: