dongxiegao3071 2013-09-25 11:20
浏览 26
已采纳

如何根据PHP 5.3中另一个数组中的值对数组元素数组进行排序?

I have an array which holds around 5000 array elements, each in the following format:

Array
        (
            [keywordid] => 98
            [keyword] => sample keyword 34
            [type] => NATURAL
            [longname] => UK
        )

I have a second array which holds numerical values such as the following:

Array
(
    [0] => 55
    [1] => 56
    [2] => 57
    [3] => 58
    [4] => 59
    [5] => 1065
    [6] => 1066
    [7] => 1067
    [8] => 1083
)

Each value in the array above corresponds to the 'keywordid' value within each array of the first array. I want to sort the first array, so that those arrays whose keywordid has a value matching an element in the second array, appear first and the rest of the arrays appear afterwards in no specified order. How do I accomplish this? I am using PHP 5.3, backwards compatibility is not a requirement.

Appreciate the help.

  • 写回答

2条回答 默认 最新

  • dounianji7883 2013-09-25 11:27
    关注

    I would probably use usort

    usort($array1, function($a, $b) use($array2) {
        $k1 = array_search($a['keywordid'], $array2);
        $k2 = array_search($b['keywordid'], $array2);
    
        if ($k1 == $k2) {
            return 0;
        }
        return ($k1 < $k2) ? -1 : 1;
    });
    

    There is probably a better way but that came to mind first.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿