Home > Article > Backend Development > How to merge these three arrays into one array? Please give me some ideas or code. Thank you.
How to add values in multiple arrays?
How to add values in multiple arrays?
You can use array_reduce(array, processing function, initial value)
array_reduce — Iteratively reduce an array to a single value using a callback function
<code class="php"><?php $arr = [ [ [ 'count' => 1 ] ], [ [ 'count' => 2 ], [ 'count' => 67 ], ] , [ [ 'count' => 3 ], [ 'count' => 2 ], ], ]; $sum = array_reduce($arr, function($currentSumOuter, $itemOuter) { // 這裡是各組中的 count 總和 // 返回結構是 [ 'count' => 總和 ] $sumInner = array_reduce($itemOuter, function($currentSumInner, $itemInner) { return [ 'count' => $itemInner['count'] + $currentSumInner['count'] ]; }, 0); // 這裡再按照原先結構,把各組總和再次總和 return [ [ 'count' => $currentSumOuter[0]['count'] + $sumInner['count'] ] ]; }, 0); echo '<pre class="brush:php;toolbar:false">'; print_r($sum); echo '';