duanjiao7440 2017-08-28 02:28
浏览 199
已采纳

如何在PHP中获取数组值的子集?

Given:

$info = ['abc'=>'xyz', '123'=>'456', 'vowels'=>'aeiou'];  //complete data array
$keys = ['abc','123'];  //list of keys I'm interested in getting the VALUES for

What's the best way to get an array like this (no KEYS in it):

['xyz','456']

Currently, I have this, but feel there might be some other way with PHP's built-in array functions:

$result = [];

foreach ($keys as $key) {
    $result[] = $info[$key];
}

return $result;

Other answers describe a 'pluck' type function, but those all return keys too... I only want the values.

Update: The answer seems to be a combination of two responses below:

array_values(array_intersect_key($info,array_flip($keys)));
  • 写回答

1条回答 默认 最新

  • dopii22884 2017-08-28 02:58
    关注

    Nothing particularly bad about your approach, but here are a couple of alternatives

    $info = ['abc'=>'xyz', '123'=>'456', 'vowels'=>'aeiou'];  //complete data array
    $keys = ['abc','123'];  //list of keys I'm interested in
    
    $out=array_intersect_key($info,array_flip($keys));
    
    print_r($out);
    

    Array ( [abc] => xyz [123] => 456 )

    OR

    $out= array_map(function($x) use ($info) { return $info[$x]; }, $keys);
    
    print_r($out);
    

    Array ( [0] => xyz [1] => 456 )

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,