简体   繁体   English

PHP-基于另一个数组对数组进行排序?

[英]PHP-Sort array based on another array?

OK, I already got this question in stackoverflow but sadly it's in javascript - Javascript - sort array based on another array好的,我已经在 stackoverflow 中遇到了这个问题,但遗憾的是它在 javascript - Javascript - sort array based on another array

and I want it in PHP我想要它在 PHP

$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

to match the arrangement of this array:匹配这个数组的排列:

sortingArr = array("5","4","3","2","1");

and the output I'm looking for:和我正在寻找的 output:

$data = array(
    "item3"=>"5",
    "item5"=>"4",
    "item2"=>"3",
    "item4"=>"2",
    "item1"=>"1"
 );

Any idea how this can be done?知道如何做到这一点吗? Thanks.谢谢。

For a detailed answer, why array_multisort does not match your needs, view this answer, please: PHP array_multisort not sorting my multidimensional array as expected有关详细答案,为什么 array_multisort 不符合您的需求,请查看此答案: PHP array_multisort 未按预期对我的多维数组进行排序

In short: You want to sort an array based on a predefined order.简而言之:您想根据预定义的顺序对数组进行排序。 The Answer is also given over there, but i copied one solution to this answer, too:那里也给出了答案,但我也复制了这个答案的一个解决方案:

Use usort and array_flip , so you be able to turn your indexing array (ValueByPosition) into a PositionByValue Array.使用usortarray_flip ,这样您就可以将索引数组(ValueByPosition) 转换为PositionByValue数组。

    $data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

usort($data, "sortByPredefinedOrder");

function sortByPredefinedOrder($leftItem, $rightItem){
  $order = array("5","4","3","2","1");

  $flipped = array_flip($order);

  $leftPos = $flipped[$leftItem];
  $rightPos = $flipped[$rightItem];
  return $leftPos >= $rightPos;   
}

print_r($data);
// usort: Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )
// uasort: Array ( [item3] => 5 [item5] => 4 [item2] => 3 [item4] => 2 [item1] => 1 )

However this would require you to predict all possible items inside the predefined order array, or thread other items in an appropriate way.但是,这需要您预测预定义订单数组中的所有可能项目,或者以适当的方式将其他项目串起来。

If you want to maintain the assoc keys, use uasort instead of usort .如果要维护uasort键,请使用uasort而不是usort

Pretty simple ?很简单?

$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

$sortingArr = array("5","4","3","2","1");

$result = array(); // result array
foreach($sortingArr as $val){ // loop
    $result[array_search($val, $data)] = $val; // adding values
}
print_r($result); // print results

Output:输出:

Array
(
    [item3] => 5
    [item5] => 4
    [item2] => 3
    [item4] => 2
    [item1] => 1
)

Look at my following snippet to sort your array based on another array:查看我的以下代码段,根据另一个数组对数组进行排序:

$res_arr = array(); 
for ($i = 0; $i < count($sortingArr); $i++) {
     for ($j = 0; $j < count($data); $j++) {
          if($data[$j] == $sortingArr[$i]) {
             $res_arr[] = $data[$j];
             break;
          }
     }
}
// $res_array is your sorted array now

using usort() the right way i think以我认为the right way使用usort()

Sort an array by values using a user-defined comparison function使用用户定义的比较函数按值对数组进行排序

you can do as follow:你可以这样做:

$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);

$sortingArr = array("5","4","3","2","1");

$keys = array_flip($sortingArr);

usort($data, function ($a, $b) use ($keys) {
    return $keys[$a] > $keys[$b] ? 1 : -1;
});

print_r($data);

// Output
// Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 )

live example: https://3v4l.org/75cnu现场示例: https : //3v4l.org/75cnu

Look at code snippet to make a multidimensional array sort in order of input查看代码片段以按输入顺序对多维数组进行排序

$input_format_list = [4, 1];
$data = array(
    "0" => array(
        "School" => array(
            "id" => 1,
             "name" => "ST.ANN'S HIGH SCHOOL",
        )
    ),     
    "1" => array(
        "School" => array(
            "id" => 4,
            "name" => "JYOTI VIDHYA VIHAR",
        )
    )
);   

$result = array(); // result array
foreach($input_format_list as $key => $value){ // loop
    foreach ($data as $k => $val) {
        if ($data[$k]['School']['id'] === $value) {
           $result[$key] = $data[$k];
        }
    }            
}            
return $result;

Take a look at array_multisort .看看array_multisort I'm not completely sure how to use it, as I have never found a practical use for it (I prefer to use usort to clearly define my terms), but it might work for you.我不完全确定如何使用它,因为我从未找到它的实际用途(我更喜欢使用usort来明确定义我的术语),但它可能对您有用。

<?php 
$data = array(
   "item1"=>"1",
   "item2"=>"3",
   "item3"=>"5",
   "item4"=>"2",
   "item5"=>"4"
);
$result=array_flip($data);

krsort($result);

$result=array_flip($result);

print_r($result);

//use rsort for the index array

$sortingArr = array("5","4","3","2","1");

print_r($sortingArr);

I'm pretty proud of my solution:我为我的解决方案感到非常自豪:

uasort($data, function($a, $b) use ($sortingArr) {  
    return array_search($a, $sortingArr) <=> array_search($b, $sortingArr);
});

Working example: https://3v4l.org/bbIk2工作示例: https : //3v4l.org/bbIk2

  1. It uses uasort to maintain the key-value associations as the OP requested.它使用uasort来维护 OP 请求的键值关联。 (unlike @hassan's otherwise elegant solution) (与@hassan 其他优雅的解决方案不同)
  2. It doesn't require that every element in the $data array be present in the sorting array.它不要求 $data 数组中的每个元素都存在于排序数组中。 (like @HamZa's solution) (如@HamZa 的解决方案)
  3. It's brief.很简短。
  4. It uses the spaceship operator <=> for comparison instead of more verbose logic.它使用飞船运算符<=>进行比较,而不是更冗长的逻辑。

Code:代码:

Expanding on the Answer of Andrew, if you want the undefined entries in the sorting array to appear at the end of the output array:扩展安德鲁的答案,如果您希望排序数组中的未定义条目出现在 output 数组的末尾:

uasort($currentTags, function ($a, $b) use ($sortingArr) {
    if (in_array($a, $sortingArr) && !in_array($b, $sortingArr)) return -1;
    if (!in_array($a, $sortingArr) && in_array($b, $sortingArr)) return 1;
    if (!in_array($b, $sortingArr)) return -1;
    return array_search($a, $sortingArr) <=> array_search($b, $sortingArr);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM