most effecient way to order an array by sub elements?

前端 未结 2 1735
春和景丽
春和景丽 2020-12-20 04:48

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 wonderin

相关标签:
2条回答
  • 2020-12-20 05:41

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

    0 讨论(0)
  • 2020-12-20 05:43

    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].

    0 讨论(0)
提交回复
热议问题