Khalid Khalid - 5 months ago 9
PHP Question

Best way to sort multidimensionnal array

I have a multidimentionnal array like this example

$arr = array (
range(9,4),
range(8,0),
range(2,7),
range(-1,17)
);


after showing its content I get this

9 8 7 6 5 4
8 7 6 5 4 3 2 1 0
2 3 4 5 6 7
-1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17


Now the result I want to get is this

-1 0 0 1 1 2
2 2 3 3 3 4 4 4 4
5 5 5 5 6 6
6 6 7 7 7 7 8 8 8 9 9 10 11 12 13 14 15 16 17


I defined a function that sorts the array and returns the result I need, but I want to know if there is a simple way to do it using predefined functions or a simple and fast algorithm

this is my function

function sort_multi($arr)
{
$length = 0;
foreach ($arr as $value)
$length += count($value);

$sorted = false;
while(!$sorted)
{
$x = 0;
$y = 0;
$sorted = true;
while(($x+$y)<($length-1) && isset($arr[$x][$y]))
{
$new_x = isset($arr[$x][$y+1])?$x:($x+1);
$new_y = isset($arr[$x][$y+1])?($y+1):0;
if(($new_x+$new_y)<$length && isset($arr[$new_x][$new_y]))
if($arr[$x][$y] > $arr[$new_x][$new_y])
{
perm($arr[$x][$y], $arr[$new_x][$new_y]);
$sorted=false;
}
$x = $new_x;
$y = $new_y;
}
}

return $arr;
}


the definition of
perm
is

function perm(&$a,&$b)
{
$inter = $a;
$a = $b;
$b = $inter;
}

Answer

I don't know which is the best way. But you can do it brute force: Sample Output

$arr = array (
    range(9,4),
    range(8,0),
    range(2,7),
    range(-1,17),
);

// simple checking of number of items per batch (since this is sort of like array_chunk, but jagged)
$chunks = array_map(function($batch){ return count($batch); }, $arr);
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($arr)) as $v) {
    $values[] = $v; // simple flattening
}
sort($values); // sort ascending (prepping)
foreach($chunks as $key => $batch) {
    // number of items in a batch
    // simple cutting (i can't find the function for this, i think there is)
    for($x = 0; $x < $batch; $x++) {
        $final[$key][] = $values[$x];
        unset($values[$x]);
    }
    $values = array_values($values); // reindex again (resetter)
}

echo '<pre>';
print_r($final);