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 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建