Home  >  Article  >  Backend Development  >  How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

WBOY
WBOYOriginal
2016-08-04 09:19:591901browse

How to add values ​​in multiple arrays?

How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

Reply content:

How to add values ​​in multiple arrays?

How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

How to merge these three arrays into one array? Please give me some ideas or code. Thank you.

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 '
';
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn