array_reduce()不能作为关联数组"reducer"使用对于PHP? [英] array_reduce() can't work as associative-array "reducer" for PHP?

查看:151
本文介绍了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.= "\n\t<row". join('',array_values($row)) ."/>";

带有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()不支持关联数组(为什么?).

PS: apparently PHP's array_reduce() not support associative arrays (why??).

推荐答案

首先,array_reduce()与关联数组一起使用,但是您没有机会访问回调函数中的键,仅访问值.

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 it's first usage.
array_walk($array, function($val, $key) use(&$result) {
    $result .= "$key=\"$val\"";
});
echo $result;

顺便说一句,同样您的原始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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆