PHP's array_map including keys

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

    A closure would work if you only need it once. I'd use a generator.

    $test_array = [
        "first_key" => "first_value", 
        "second_key" => "second_value",
    ];
    
    $x_result = (function(array $arr) {
        foreach ($arr as $key => $value) {
            yield "$key loves $value";
        }
    })($test_array);
    
    var_dump(iterator_to_array($x_result));
    
    // array(2) {
    //   [0]=>
    //   string(27) "first_key loves first_value"
    //   [1]=>
    //   string(29) "second_key loves second_value"
    // }
    

    For something reusable:

    function xmap(callable $cb, array $arr)
    {
        foreach ($arr as $key => $value) {
            yield $cb($key, $value);
        }
    }
    
    var_dump(iterator_to_array(
        xmap(function($a, $b) { return "$a loves $b"; }, $test_array)
    ));
    

提交回复
热议问题