dounao5856 2016-10-03 17:54
浏览 36
已采纳

在PHP中,在给定原始顺序时,对已排序的对象数组进行分类的最佳方法是什么?

Let's say I have one array of ID numbers in a desired particular order. I have a second array of objects that were sorted by an ID property from the first array.

$array1 = [3,4,2,1,5];

$array2 = [
    ["id" => 1, "data" => "one"],
    ["id" => 2, "data" => "two"],
    ["id" => 3, "data" => "fre"],
    ["id" => 4, "data" => "foe"],
    ["id" => 5, "data" => "fie"]
];

In PHP, what is the best way of 'unsorting' or reverting the second array to the original order of the first array?

The closest answer I can find without using a sort is:

$array1_flipped = array_flip($array1);

$array2_unsorted = array();

for($i = 0; $i < count($array1); $i++) {
  $array2_unsorted[$array1_flipped[$array2[$i]['id']]] = $array2[$i];
}

return($array2_unsorted);

Edit: For those interested, here is how the question arose. The first array is a list of IDs to be displayed in a particular order. The second array is the return of the MySQL call WHERE id IN $array2, which is returned sorted. However, the second array needs to be resorted back into the order of the first array. Due to size issues, I was hoping to be able to remap the second array using the keys and values of the first array without sorting.

  • 写回答

2条回答 默认 最新

  • dsgdg54ef4365 2016-10-04 00:55
    关注

    I found the solution by introducing a third array and using a method similar to Gauss-Jordan elimination. While this is beautiful, I wish there was a one-step algorithm for this. I'll award the correct answer to anyone who finds it.

    $array1 = [3,4,2,1,5];
    $array2 = [
        ["id" => 1, "data" => "one"],
        ["id" => 2, "data" => "two"],
        ["id" => 3, "data" => "fre"],
        ["id" => 4, "data" => "foe"],
        ["id" => 5, "data" => "fie"]
    ];
    // Placeholder sorted ascending array (e.g. $array3 = [1,2,3,4,5])
    $array3 = range(1,count($array1));
    
    array_multisort($array1, $array3);
    // Now $array3 = [4,3,1,2,5], the inverse map of an $array1 sort
    
    array_multisort($array3, $array2);
    
    return $array2;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目