排序多维数组两次

时间:2014-04-01 08:27:16

标签: php arrays multidimensional-array

我已经在从低到高的值距离上对多维数组进行了排序。这是输出的一个例子:(实际输出有大约20或30个数组)。

阵     (

[0] => Array
    (
        [id] => 1
        [distance] => 5
        [sponsor] => 0
    )

[1] => Array
    (
        [id] => 20
        [distance] => 8
        [sponsor] => 1 
    )

[2] => Array
    (
        [id] => 25
        [distance] => 10
        [sponsor] => 0 
    )

[3] => Array
    (
        [id] => 78
        [distance] => 25
        [sponsor] => 1 
    )

在从低到高的距离排序之后,如果赞助商= 1,我想优先考虑。这是首选输出:

阵     (

[0] => Array
    (
        [id] => 20
        [distance] => 8
        [sponsor] => 1
    )

[1] => Array
    (
        [id] => 78
        [distance] => 25
        [sponsor] => 1 
    )

[2] => Array
    (
        [id] => 1
        [distance] => 5
        [sponsor] => 0 
    )

[3] => Array
    (
        [id] => 25
        [distance] => 10
        [sponsor] => 0 
    )

赞助商是0或1.我如何解决这个问题?我想到的是,在排序距离之前,我应该根据赞助商(0,1)将数组拆分为2个数组,对距离上的两个数组进行排序,然后将它们与赞助商= 1合并在新的多维数组的顶部。这是这样做的吗?

感谢您的投入。

5 个答案:

答案 0 :(得分:3)

这是usort建议的略微修改版本。假设源数组名为$ arr:

usort(
  $arr, function($a, $b) {
     if ( $a['sponsor'] == $b['sponsor'] ) {
        if ( $a['distance'] == $b['distance'] ) {
            return 0;
        }
        return $a['distance'] < $b['distance'] ? -1 : 1;
     }
     return $a['sponsor'] > $b['sponsor'] ? -1 : 1;
  }
);

答案 1 :(得分:1)

您必须将原始数组拆分为2个数组:1st包含sponsor=1,2nd包含sponsor=0。然后单独对它们进行排序并合并。

不知怎的这样:

$array1 = array_filter($array, function ($v) { return $v['sponsor'] == 1; });
$array2 = array_filter($array, function ($v) { return $v['sponsor'] == 0; });

function cmp($a, $b) {
    return $a['distance'] < $b['distance']? -1 : 1;
}

usort($array1, cmp);
usort($array2, cmp);
$result = array_merge($array1, $array2);

答案 2 :(得分:0)

这样可行,但如果您使用stable sorting algorithm,那么您可以先按距离排序,然后按赞助商降序排序,您将获得所需的结果。

答案 3 :(得分:0)

您可以使用array_multisort()函数来实现所需的功能:

<?php

$arr = [
    ['id' => 1, 'distance' => 5, 'sponsor' => 0],
    ['id' => 20, 'distance' => 8, 'sponsor' => 1],
    ['id' => 25, 'distance' => 10, 'sponsor' => 0],
    ['id' => 78, 'distance' => 25, 'sponsor' => 1],
];

$sponsor = array_column($arr, 'sponsor');
$distance  = array_column($arr, 'distance');

// rearrange $arr by sponsor DESC and then by distance ASC
array_multisort($sponsor, SORT_DESC, $distance, SORT_ASC, $arr);

print_r($arr);

答案 4 :(得分:-1)

试试这个:

  <?php
   $ar = array(
   array("10", 11, 100, 100, "a"),
   array(   1,  2, "2",   3,   1)
   );
   array_multisort($ar[0], SORT_ASC, SORT_STRING,
   $ar[1], SORT_NUMERIC, SORT_DESC);
   var_dump($ar);
   ?> 

  <?php
  $ar1 = array(10, 100, 100, 0);
  $ar2 = array(1, 3, 2, 4);
  array_multisort($ar1, $ar2);
  var_dump($ar1);
  var_dump($ar2);
  ?>