dty3416 2019-05-05 12:48
浏览 73
已采纳

使用另一个数组的键值获取数组的值

I have an array with some values (numeric values):

$arr1 = [1, 3, 8, 12, 23]

and I have another associative array that a key (which matches to a value of $arr1) correspond to a value. This array may contain also keys that don't match with $arr1.

$arr2 = [1 => "foo", 2 => "foo98", 3 => "foo20", 8 => "foo02", 12 => "foo39", 15 => "foo44", 23 => "foo91", 34 => "foo77"]

I want as return the values of $arr2 specifying as key the values of $arr1:

["foo", "foo20", "foo02", "foo39", "foo91"]

If possible, all this, without loops, using just PHP array native functions (so in an elegant way), or at least with the minimum number of loops possible.

  • 写回答

2条回答 默认 最新

  • duanhuancong1969 2019-05-05 13:01
    关注

    Minimal loop is simple - 1. as:

    foreach($arr1 as $k) {
        $res[] = $arr2[$k];
    }
    

    You can do that with array_walk but I think this simple way is more readable.

    If you insist you can do with array_filter + array_values + in_array as:

    $res = array_values(array_filter($arr2,
        function ($key) use ($arr1) { return in_array($key, $arr1);},
        ARRAY_FILTER_USE_KEY
    ));
    

    You can see this for more about filtering keys

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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化