PHP's array_map including keys

前端 未结 18 2770
抹茶落季
抹茶落季 2020-11-30 19:31

Is there a way of doing something like this:

$test_array = array(\"first_key\" => \"first_value\", 
                    \"second_key\" => \"second_valu         


        
18条回答
  •  时光说笑
    2020-11-30 20:07

    By "manual loop" I meant write a custom function that uses foreach. This returns a new array like array_map does because the function's scope causes $array to be a copy—not a reference:

    function map($array, callable $fn) {
      foreach ($array as $k => &$v) $v = call_user_func($fn, $k, $v);
      return $array;
    }
    

    Your technique using array_map with array_keys though actually seems simpler and is more powerful because you can use null as a callback to return the key-value pairs:

    function map($array, callable $fn = null) {
      return array_map($fn, array_keys($array), $array);
    }
    

提交回复
热议问题