PHP#39;s array_map including keys(PHP 的 array_map 包括键)
问题描述
有没有办法做这样的事情:
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)));
但是不是调用array_keys
和array_values
,而是直接传递$test_array
变量?
But instead of calling array_keys
and array_values
, directly passing the $test_array
variable?
所需的输出是:
array(2) {
[0]=>
string(27) "first_key loves first_value"
[1]=>
string(29) "second_key loves second_value"
}
推荐答案
不使用 array_map,因为它不处理键.
Not with array_map, as it doesn't handle keys.
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);
// array(2) {
// ["first_key"]=>
// string(27) "first_key loves first_value"
// ["second_key"]=>
// string(29) "second_key loves second_value"
// }
它确实改变了作为参数给出的数组,所以它不完全是函数式编程(因为你有这样标记的问题).此外,正如评论中所指出的,这只会更改数组的值,因此键不会是您在问题中指定的键.
It does change the array given as parameter however, so it's not exactly functional programming (as you have the question tagged like that). Also, as pointed out in the comment, this will only change the values of the array, so the keys won't be what you specified in the question.
如果您愿意,您可以编写一个函数来修复上面的点,如下所示:
You could write a function that fixes the points above yourself if you wanted to, like this:
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"
// }
这篇关于PHP 的 array_map 包括键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP 的 array_map 包括键


- 覆盖 Magento 社区模块控制器的问题 2022-01-01
- 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
- 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
- Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
- PHP - if 语句中的倒序 2021-01-01
- openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
- PHP foreach() 与数组中的数组? 2022-01-01
- 如何在 Symfony2 中正确使用 webSockets 2021-01-01
- 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01