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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧