1

I have a multidimensional array.

$array[0] = array(1, 8, 2);    
$array[1] = array(5, 6, 15);
$array[2] = array(-8, 2, 1025);

I am wondering what the most efficient way to order the parent array by a particular property of it's sub array. For example, I want to put them in ascending order of $sub_array[1], so the parent array would be ordered 2,1,0.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148

2 Answers2

2

Use http://www.php.net/manual/en/function.usort.php and write a callback function that implements the sort condition you want.

halfdan
  • 33,545
  • 8
  • 78
  • 87
2

sort and its cousins have variations where you can supply your own sorting callback function: usort, uasort (which maintains indexes), and uksort (which sorts on the keys. You'll have to create your own sorting callback to do what you want to do here.

function sort_by_subarray($a, $b)
{
  // $a and $b are elements of $array that are being compared against
  // each other to be sorted

  if (!isset($a[1]) || !isset($b[1]))
  {
    // Do something if $a[1] or $b[1] is undefined
    // Your question doesn't define what the behaviour here should be
  }
  else
  {
    if ($a[1] == $b[1]) return 0;     // the elements are the same
    return ($a[1] < $b[1]) ? -1 : 1;  // otherwise, sort from lowest to highest
  }
}

$array = array(
  array(1, 8, 2),
  array(5, 6, 15),
  array(-8, 2, 1025)
);
uasort($array, "sort_by_subarray");

/* Results in:
Array
(
    [2] => Array
        (
            [0] => -8
            [1] => 2
            [2] => 1025
        )

    [1] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 15
        )

    [0] => Array
        (
            [0] => 1
            [1] => 8
            [2] => 2
        )

)
*/

Note that my function will sort two subarrays as being equal if $subarray[1] is equal, so if you want to be more specific, you can add more rules for when $a[1] == $b[1].

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
  • almost there, but I need something that will sort by one specific value with the sub_array - So if array[1]->sub_array[2] > array[2]->sub_array[2] then array[1] trumps array [2] – Mild Fuzz Sep 11 '10 at 15:19
  • @Mild Fuzz: that's what my sorting function should be doing (see the results). Unless I misunderstood something? – Daniel Vandersluis Sep 11 '10 at 15:27
  • Is there any good resource for understanding the custom callback functions better? – Mild Fuzz Sep 13 '10 at 22:03
  • A custom callback function is just a function that you write yourself that you pass to another function. The manual page for usort should help. – Daniel Vandersluis Sep 14 '10 at 02:15