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.= '/>';
How to do in an elegant way the same thing, but using array_reduce()
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)) ."/>";
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: apparently PHP's array_reduce()
not support associative arrays (why??).