dty3416 2019-05-05 04: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 05: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条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部