array_reduce() can#39;t work as associative-array quot;reducerquot; for PHP?(array_reduce() 不能用作关联数组“reducer;对于 PHP?)
问题描述
我有一个关联数组 $assoc
,并且需要在这个上下文中将它简化为一个字符串
I have an associative array $assoc
, and need to reduce to it to a string, in this context
$OUT = "<row";
foreach($assoc as $k=>$v) $OUT.= " $k="$v"";
$OUT.= '/>';
如何以一种优雅的方式同样的事情,但使用 array_reduce()代码>
How to do in an elegant way the same thing, but using array_reduce()
与 array_walk()
函数接近相同的算法(性能较低且易读性较低),
Near the same algorithm (lower performance and lower legibility) with array_walk()
function,
array_walk( $row, function(&$v,$k){$v=" $k="$v"";} );
$OUT.= "
<row". join('',array_values($row)) ."/>";
Ugly 使用 array_map()
解决方案(并且再次将 join()
作为 reducer):
Ugly solution with array_map()
(and again join()
as reducer):
$row2 = array_map(
function($a,$b){return array(" $a="$b"",1);},
array_keys($row),
array_values($row)
); // or
$OUT ="<row ". join('',array_column($row2,0)) ."/>";
PS:显然 PHP 的 array_reduce()
不支持关联数组(why??).
PS: apparently PHP's array_reduce()
not support associative arrays (why??).
推荐答案
首先,array_reduce()
适用于关联数组,但是你没有机会在回调函数中访问key,只有值.
First, array_reduce()
works with associative arrays, but you don't have any chance to access the key in the callback function, only the value.
您可以使用 use
关键字通过在闭包中的引用来访问 $result
,如下面的 array_walk()
示例所示.这将非常类似于 array_reduce()
:
You could use the use
keyword to access the $result
by reference in the closure like in the following example with array_walk()
. This would be very similar to array_reduce()
:
$array = array(
'foo' => 'bar',
'hello' => 'world'
);
// Inject reference to `$result` into closure scope.
// $result will get initialized on its first usage.
array_walk($array, function($val, $key) use(&$result) {
$result .= " $key="$val"";
});
echo "<row$result />";
顺便说一句,imo 你原来的 foreach 解决方案看起来也很优雅.此外,只要阵列保持中小尺寸,就不会有明显的性能问题.
Btw, imo your original foreach solution looks elegant too. Also there will be no significant performance issues as long as the array stays at small to medium size.
这篇关于array_reduce() 不能用作关联数组“reducer";对于 PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:array_reduce() 不能用作关联数组“reducer";对于 PHP?


- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01