duanganleng0577 2014-10-30 10:35
浏览 143
已采纳

PHP:根据另一个不同长度的数组对数组进行排序

I have two arrays of different length:

$paths_table = array("TS-0007_a.jpg", "TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0041_a.JPG", "TS-0041_b.JPG");

$order_table = array("TS-0040","TS-0007","TS-0041");

and I want to sort the first one using the second so that the output will be the array

$final_table = array("TS-0040_a.JPG", "TS-0040_b.JPG", "TS-0040_f.JPG", "TS-0007_a.jpg", TS-0041_a.JPG", "TS-0041_b.JPG")

Assuming that I'm going to use

strpos($paths_table[$i], $order_table[$j]);

to check if the string of $order_table is included in any of the $paths_table.

How can I accomplish this?

  • 写回答

2条回答 默认 最新

  • dozc1071 2014-10-30 11:03
    关注

    Preprocess the array so that each item contains an index of its prefix (that is, turn 'TS-0007_a.jpg' into [1,'TS-0007_a.jpg']):

    foreach($paths_table as &$v) {
        foreach($order_table as $n => $o)
            if(strpos($v, $o) === 0) {
                $v = [$n, $v];
                break;
            }
    }
    

    sort the array:

    sort($paths_table);
    

    and remove indexes:

    foreach($paths_table as &$v)
        $v = $v[1];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程