note 109320 modified in function.array-reduce by danbrown
| From: | danbrown@php.net | Date: | Mon, 16 Jul 2012 15:46:55 +0000 |
| Subject: | note 109320 modified in function.array-reduce by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-189225@lists.php.net to get a copy of this message | ||
If you want something elegant in your code, when dealing with reducing array, just unshift first
element, and use it as initial, because if you do not do so, you will + first element with first
element: <?php $arr =
array( array('min' => 1.5456, 'max'
=> 2.28548, 'volume' => 23.152),
array('min' => 1.5457, 'max' => 2.28549,
'volume' => 23.152), array('min'
=> 1.5458, 'max' => 2.28550, 'volume' =>
23.152), array('min' => 1.5459, 'max'
=> 2.28551, 'volume' => 23.152),
array('min' => 1.5460, 'max' => 2.28552,
'volume' =>
23.152), ); $initial =
array_shift($arr); $t = array_reduce($arr, function($result,
$item) { $result['min'] = min($result['min'],
$item['min']); $result['max'] =
max($result['max'], $item['max']);
$result['volume'] +=
$item['volume']; return
$result; }, $initial); ?>
--was--
If you want something elegant in your code, when dealing with reducing array, just unshift first
element, and use it as initial, because if you do not do so, you will + first element with first
element:
$arr = array(
array('min' => 1.5456, 'max' => 2.28548, 'volume' =>
23.152),
array('min' => 1.5457, 'max' => 2.28549, 'volume' =>
23.152),
array('min' => 1.5458, 'max' => 2.28550, 'volume' =>
23.152),
array('min' => 1.5459, 'max' => 2.28551, 'volume' =>
23.152),
array('min' => 1.5460, 'max' => 2.28552, 'volume' =>
23.152),
);
$initial = array_shift($arr);
$t = array_reduce($arr, function($result, $item) {
$result['min'] = min($result['min'], $item['min']);
$result['max'] = max($result['max'], $item['max']);
$result['volume'] += $item['volume'];
return $result;
}, $initial);
http://php.net/manual/en/function.array-reduce.php