Sorting a Multidimensional array
I need to sort an array that can look like this:
$array[4][0] = array('id' => 1, 'value' => 2);
$array[3][2] = array('id' => 0, 'value' => 3);
$array[4][1] = array('id' => 1, 'value' => 0);
$array[1][3] = array('id' => 2, 'value' => 1);
$array[1][1] = array('id' => 3, 'value' => 0);
$array[3][0] = array('id' => 2, 'value' => 1);
$array[3][1] = array('id' => 1, 'value' =&开发者_StackOverflowgt; 0);
$array[1][2] = array('id' => 3, 'value' => 2);
$array[1][0] = array('id' => 2, 'value' => 1);
$array[2][1] = array('id' => 0, 'value' => 2);
$array[2][4] = array('id' => 3, 'value' => 1);
But needs to be sorted and returned as this:
$array[1][0] = array('id' => 2, 'value' => 1);
$array[1][1] = array('id' => 3, 'value' => 0);
$array[1][2] = array('id' => 3, 'value' => 2);
$array[1][3] = array('id' => 2, 'value' => 1);
$array[2][1] = array('id' => 0, 'value' => 2);
$array[2][4] = array('id' => 3, 'value' => 1);
$array[3][0] = array('id' => 2, 'value' => 1);
$array[3][1] = array('id' => 1, 'value' => 0);
$array[3][2] = array('id' => 0, 'value' => 3);
$array[4][0] = array('id' => 1, 'value' => 2);
$array[4][1] = array('id' => 1, 'value' => 0);
Can anyone help me? It needs to sort both indexes of the array from lowest to highest index value. Sounds simple enough, but I'm having the hardest time trying to figure this out, while still keeping the values intact.
Please help someone...
A quick'n'dirty solution might look something like:
// Sort the outer array
ksort($array);
// Sort each inner array
foreach($array as &$innerArray)
{
ksort($innerArray);
}
You want to sort it by key then, and not by values: http://se.php.net/manual/en/function.ksort.php or http://se.php.net/manual/en/function.uksort.php
Edit, Example;
function sorter(array &$multidimensional) {
foreach ($multidimensional as &$current) {
if (is_array($current))
sorter($current);
}
ksort($multidimensional);
}
Something like this should do it:
function ksort_recursive(&$arr) {
foreach($arr as $key => &$value) {
if(is_array($value)) {
ksort_recursive($value);
}
} unset($value);
ksort($arr);
}
ksort_recursive($array);
精彩评论