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 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?