phparrayssortingmultidimensional-array

Sort an array of arrays so that larger arrays ar first without preserving first level indexes


$arr1 = [1, 2, 3, 8];
$arr2 = [1, 2, 4, 9, 10];
$arr3 = [1, 2, 5, 11, 12];
$arrs = [$arr1, $arr2, $arr3];
arsort($arrs);

I have sorted the $arrs to change it to $arr3, $arr2, $arr1, My problem is that it kept its Array Key as it is, I want to rewrite these keys by its new order, so instead of

[2]$arr3 [1]$arr2 [0]$arr1

it becomes

[0]$arr3 [1]$arr2 [2]$arr1

I thought about explode()ing then implode()ing the array again But it didn't work because it is a MDArray like the following $arrs = implode(explode($arrs)); after arsort().

What is the best and shortest way to re[write][make] the array keys?


Solution

  • Just simply use array_values;

    $arr1 = [1, 2, 3, 8];
    $arr2 = [1, 2, 4, 9, 10];
    $arr3 = [1, 2, 5, 11, 12];
    $arrs = [$arr1, $arr2, $arr3];
    arsort($arrs);
    
    $arrs  = array_values($arrs);
    

    This will reset the keys based on the order.