PHP Built-in Method to Get Array Values Given a Li

2020-02-14 07:40发布

问题:

I have an 'dictionary' array such as this:

  $arr['a']=5;
  $arr['b']=9;
  $arr['as']=56;
  $arr['gbsdfg']=89;

And I need a method that, given a list of the array keys, I can retrieve the corresponding array values. In other words, I am looking for a built-in function for the following methods:

function GetArrayValues($arrDictionary, $arrKeys)
{
  $arrValues=array();
  foreach($arrKeys as $key=>$value)
  {
     $arrValues[]=$arrDictionary[$key]
  }
  return $arrValues;
}

I am so sick of writing this kind of tedious transformation that I have to find a built-in method to do this. Any ideas?

回答1:

array_intersect_key



回答2:

If you have an array of keys as values you can use array_intersect_key combined with array_flip. For example:

$values = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$keys   = ['a', 'c'];

array_intersect_key($values, array_flip($keys));
// ['a' => 1, 'c' => 3]


标签: php arrays