Get array values by keys

后端 未结 3 1379
春和景丽
春和景丽 2020-12-13 06:01

I am searching for a built in php function that takes array of keys as input and returns me corresponding values.

for e.g. I have a following array



        
相关标签:
3条回答
  • 2020-12-13 06:11

    I think you are searching for array_intersect_key. Example:

    array_intersect_key(array('a' => 1, 'b' => 3, 'c' => 5), 
                        array_flip(array('a', 'c')));
    

    Would return:

    array('a' => 1, 'c' => 5);
    

    You may use array('a' => '', 'c' => '') instead of array_flip(...) if you want to have a little simpler code.

    Note the array keys are preserved. You should use array_values afterwards if you need a sequential array.

    0 讨论(0)
  • 2020-12-13 06:27
    foreach($input_arr as $key) {
        $output_arr[] = $mapping[$key];
    }
    

    This will result in $output_arr having the values corresponding to a list of keys in $input_arr, based on the key->value mapping in $mapping. If you want, you could wrap it in a function:

    function get_values_for_keys($mapping, $keys) {
        foreach($keys as $key) {
            $output_arr[] = $mapping[$key];
        }
        return $output_arr;
    }
    

    Then you would just call it like so:

    $a = array('a' => 1, 'b' => 2, 'c' => 3);
    $values = get_values_for_keys($a, array('a', 'c'));
    // $values is now array(1, 3)
    
    0 讨论(0)
  • 2020-12-13 06:29

    An alternative answer:

    $keys = array("key2", "key4");
    
    return array_map(function($x) use ($arr) { return $arr[$x]; }, $keys);
    
    0 讨论(0)
提交回复
热议问题