infodigger
asked on
Sorting a multi-dimensional array
Hello,
I have the following array:
All I need to do is to sort the arrays with the [2] value so that the cities are sorted as:
City3
City1
City2
City4
City5
City0
Is that possible?
Thanks for the help!
I have the following array:
Array
(
[0] => Array
(
[0] => 3
[1] => City0
[2] => 64
)
[1] => Array
(
[0] => 6
[1] => City1
[2] => 164
)
[2] => Array
(
[0] => 7
[1] => City2
[2] => 160
)
[3] => Array
(
[0] => 8
[1] => City3
[2] => 188
)
[4] => Array
(
[0] => 9
[1] => City4
[2] => 156
)
[5] => Array
(
[0] => 10
[1] => City5
[2] => 72
)
)
All I need to do is to sort the arrays with the [2] value so that the cities are sorted as:
City3
City1
City2
City4
City5
City0
Is that possible?
Thanks for the help!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you very much for the answer!
That example uses array_multisort(), which is the built-in PHP function for doing the bulk of this work and doing it quickly and efficiently. My mdarray_sort function is just a wrapper around it. I've also used this function in the past, which supports multiple sorts (I did not write it, though):
function array_csort() { //coded by Ichier2003
$args = func_get_args();
$marray = array_shift($args);
$msortline = 'return(array_multisort(';
foreach ($args as $arg) {
$i++;
if (is_string($arg)) {
foreach ($marray as $row) {
$sortarr[$i][] = $row[$arg];
}
} else {
$sortarr[$i] = $arg;
}
$msortline .= '$sortarr['.$i.'],';
}
$msortline .= '$marray));';
eval($msortline);
return $marray;
}
Open in new window