PHP的array_map包含键 [英] PHP's array_map including keys
本文介绍了PHP的array_map包含键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有这样做的方法:
$ test_array = array(first_key=>first_value ,
second_key=>second_value);
var_dump(array_map(function($ a,$ b){return$ a loves $ b;},
array_keys($ test_array),
array_values($ test_array )));
但不是调用 array_keys
和 array_values
,直接传递 $ test_array
变量?
输出是:
array(2){
[0] =>
string(27)first_key loves first_value
[1] =>
string(29)second_key loves second_value
}
解决方案
不适用于array_map,因为它不处理键。 $ b
array_walk 的确如此:
$ test_array = array(first_key =>first_value,
second_key=>second_value);
array_walk($ test_array,function(& $ a,$ b){$ a =$ b loves $ a;});
var_dump($ test_array);
它确实改变了作为参数给出的数组,所以它不是完全的函数式编程这样的问题标签)。
如果你愿意的话,你可以自己编写一个函数。
Is there a way of doing something like this:
$test_array = array("first_key" => "first_value",
"second_key" => "second_value");
var_dump(array_map(function($a, $b) { return "$a loves $b"; },
array_keys($test_array),
array_values($test_array)));
But instead of calling array_keys
and array_values
, directly passing the $test_array
variable?
The desired output is:
array(2) {
[0]=>
string(27) "first_key loves first_value"
[1]=>
string(29) "second_key loves second_value"
}
解决方案
Not with array_map, as it doesn't handle keys.
array_walk does:
$test_array = array("first_key" => "first_value",
"second_key" => "second_value");
array_walk($test_array, function(&$a, $b) { $a = "$b loves $a"; });
var_dump($test_array);
It does change the array given as parameter however, so it's not exactly functional programming (as you have the question tagged like that).
You could write a function like that yourself if you wanted to.
这篇关于PHP的array_map包含键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文