本文介绍了基于另一个数组的 PHP 排序数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我已经在 stackoverflow 中遇到了这个问题,但遗憾的是它在 javascript 中 - Javascript - 基于另一个数组对数组进行排序

OK, I already got this question in stackoverflow but sadly it's in javascript - Javascript - sort array based on another array

我想要它在 PHP 中

and I want it in PHP

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

匹配这个数组的排列:

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

以及我正在寻找的输出:

and the output I'm looking for:

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

知道如何做到这一点吗?谢谢.

Any idea how this can be done?Thanks.

推荐答案

详细解答,为什么 array_multisort 不符合您的需求,请查看此答案:PHP array_multisort 没有将我的多维数组排序为预期

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

简而言之:您想根据预定义的顺序对数组进行排序.那里也给出了答案,但我也复制了这个答案的一个解决方案:

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:

使用usortarray_flip,这样您就可以将索引数组 (ValueByPosition) 变成PositionByValue 数组.

Use usort and array_flip, so you be able to turn your indexing array (ValueByPosition) into a PositionByValue Array.

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

如果要维护关联键,请使用 uasort 而不是 usor.

If you want to maintain the assoc keys, use uasort instead of usort.

这篇关于基于另一个数组的 PHP 排序数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:33