本文介绍了最effecient方式命令由子元素的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组。

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

我想知道什么是最有效的方式通过它的特定属性订购父数组的数组子。例如,我希望把他们在$ sub_array [1]升序排列,因此父阵列将被责令2,1,0。

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.

推荐答案

及其堂兄弟有变化,你可以提供自己的排序回调函数:的,的(即保持索引),和的(其排序上的按键,你就必须创建自己的排序回调做你想要做什么。

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
        )

)
*/

请注意,我的功能将作为是,如果相等的两个子数组排序$子数组[1]是相等的,所以如果你想更具体的,您可以添加更多的规则时, $ A [1] == $ b [1]

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

这篇关于最effecient方式命令由子元素的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:53