array_reduce() can't work as associative-array "reducer" for PHP?
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.
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 />";
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 = array(
'foo' => 'bar',
'hello' => 'world'
);
$OUT = join(" ", array_reduce(array_keys($array), function($as, $a) use ($array) {
$as[] = sprintf('%s="%s"', $a, $array[$a]); return $as;
}, array()));
I personally see nothing wrong with the foreach thing, but if you want one single expression, your map
snippet can be simplified down to
$OUT = sprintf("<row %s/>",
join(" ", array_map(
function($a, $b) { return "$a=\"$b\""; },
array_keys($assoc),
array_values($assoc)
)));
Also, since you're generating XML, it's better to use a dedicated tool, for example:
$doc = new SimpleXMLElement("<row/>");
foreach($assoc as $k => $v)
$doc->addAttribute($k, $v);
echo $doc->asXML();