douwen4401 2012-03-17 21:36
浏览 40
已采纳

通过键数组获取关联数组元素

$array1 = ['key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3']
$array2 = ['key1','key3']

I want to get all elements from array1 that has keys in array2. So the result should be:

$result = ['key1'=>'val1', 'key3'=>'val3']

I tried array_intersect_key($array1, $array2) but that doesn't work. What is the fastest way to get the above result?

Edit: Forgot to mention that array2 maybe a associative array or single dimension.

  • 写回答

3条回答 默认 最新

  • dsaff82024 2012-03-17 21:38
    关注

    You need to make key1 and key2 the keys in the second array before you can use array_intersect_key(): use array_flip() to do that

    $result = array_intersect_key($array1,array_flip($array2));
    

    EDIT

    It doesn't matter if $array2 is associative or not:

    $array1 = array('key1'=>'val1', 'key2'=>'val2', 'key3'=>'val3');
    $array2 = array('first'=>'key1','second'=>'key3');
    
    $filteredData = array_intersect_key($array1,array_flip($array2));
    var_dump($filteredData);
    

    still gives

    array
      'key1' => string 'val1' (length=4)
      'key3' => string 'val3' (length=4)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题