array_reduce() 不能用作关联数组“reducer";对于 PHP?

2022-01-14 00:00:00 mapreduce php associative-array

我有一个关联数组 $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.

相关文章