有没有办法做这样的事情:
$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
and array_values
,直接通过$test_array
多变的?
期望的输出是:
array(2) {
[0]=>
string(27) "first_key loves first_value"
[1]=>
string(29) "second_key loves second_value"
}
不适用于 array_map,因为它不处理键。
数组行走 http://www.php.net/manual/en/function.array-walk.php 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);
// array(2) {
// ["first_key"]=>
// string(27) "first_key loves first_value"
// ["second_key"]=>
// string(29) "second_key loves second_value"
// }
然而,它确实更改了作为参数给出的数组,因此它不完全是函数式编程(因为您有这样标记的问题)。另外,正如评论中指出的,这只会更改数组的值,因此键不会是您在问题中指定的值。
如果您愿意,您可以编写一个函数来修复上述问题,如下所示:
function mymapper($arrayparam, $valuecallback) {
$resultarr = array();
foreach ($arrayparam as $key => $value) {
$resultarr[] = $valuecallback($key, $value);
}
return $resultarr;
}
$test_array = array("first_key" => "first_value",
"second_key" => "second_value");
$new_array = mymapper($test_array, function($a, $b) { return "$a loves $b"; });
var_dump($new_array);
// array(2) {
// [0]=>
// string(27) "first_key loves first_value"
// [1]=>
// string(29) "second_key loves second_value"
// }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)