PHP's array_map including keys

前端 未结 18 2760
抹茶落季
抹茶落季 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:03

    I made this function, based on eis's answer:

    function array_map_($callback, $arr) {
        if (!is_callable($callback))
            return $arr;
    
        $result = array_walk($arr, function(&$value, $key) use ($callback) {
            $value = call_user_func($callback, $key, $value);
        });
    
        if (!$result)
            return false;
    
        return $arr;
    }
    

    Example:

    $test_array = array("first_key" => "first_value", 
                    "second_key" => "second_value");
    
    var_dump(array_map_(function($key, $value){
        return $key . " loves " . $value;
    }, $arr));
    

    Output:

    array (
      'first_key' => 'first_key loves first_value,
      'second_key' => 'second_key loves second_value',
    )
    

    Off course, you can use array_values to return exactly what OP wants.

    array_values(array_map_(function($key, $value){
        return $key . " loves " . $value;
    }, $test_array))
    

提交回复
热议问题