array_reduce
array_reduce() 将回调函数 callback 迭代地作用到 array 数组中的每一个单元中,从而将数组简化为单一的值。
示例一:
public function arrayReduce() { $data = [ ['a' => '10', 'b' => '30'], ['a' => '20', 'b' => '60'], ['a' => '30', 'b' => '90'], ]; // 计算所有a与b的值累加 $handle = array_reduce($data, function ($carry, $item) { $carry += $item['a'] + $item['b']; return $carry; }); return $handle; // 240 }
示例二:
public function arrayReduce() { $data = [ ['a' => '10', 'b' => '30'], ['a' => '20', 'b' => '60'], ['a' => '30', 'b' => '90'], ]; // 调用myFunction回调函数,计算所有a与b的值累加 $handle = array_reduce($data, [$this, 'myFunction']); return $handle; // 240 } function myFunction($carry, $item) { $carry += $item['a'] + $item['b']; return $carry; }