Get array values by keys

后端 未结 3 1388
春和景丽
春和景丽 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: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)
    

提交回复
热议问题