PHP's array_map including keys

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

    YaLinqo library* is well suited for this sort of task. It's a port of LINQ from .NET which fully supports values and keys in all callbacks and resembles SQL. For example:

    $mapped_array = from($test_array)
        ->select(function ($v, $k) { return "$k loves $v"; })
        ->toArray();
    

    or just:

    $mapped_iterator = from($test_array)->select('"$k loves $v"');
    

    Here, '"$k loves $v"' is a shortcut for full closure syntax which this library supports. toArray() in the end is optional. The method chain returns an iterator, so if the result just needs to be iterated over using foreach, toArray call can be removed.

    * developed by me

提交回复
热议问题