phparrayssortingmultidimensional-arraysticky

Sort rows of a 2d array to always have a specified value as the firat element


I have a very big array. Arrays within arrays. Below is a small portion of it;

[lta/] => Array(
    [2012-12-31/] => Array(
        [0] => 31_december_2012.pdf
        [1] => 31_december_2012.xls
        [2] => key_points.html
    )
    ...
)

What I need to do, is get the "key_points.html" value to always start at the top of it's array. Example;

[2012-12-31/] => Array
    (
        [2] => key_points.html            
        [0] => 31_december_2012.pdf
        [1] => 31_december_2012.xls  
    )
    ...
)

I cannot do a simple asort because I never know at which point "key_points.html" is going to appear in the array.

I tried to rename the values "key_points.html" with a view to sorting it and then un-renaming it after;

foreach ($the_array as $array_object => $array_item) {
    if ($array_item == "key_points.html") {
        $array_item = "0001_key_points.html";
    }
}

But that literally seemed to have no effect! it didn't even rename my value. I also tried the same thing with string replace;

$the_array = str_replace("key_points.html", "0001_key_points.html", $the_array);

Is there a function perhaps that allows you to specify a string, and move that to the top of each array each time if it finds it?


Solution

  • Use uasort to specify a custom comparator callback:

    uasort($array, function($a, $b) {
      if($a == 'key_points.html') return -1; // Smaller than all
      if($b == 'key_points.html') return 1;  // Larger than all
      return ($a < $b) ? -1 : 1;             // Default sorting
    });
    

    Syntax is assuming an up to date PHP (5.3+) with support for anonymous functions.