Home > Backend Development > PHP Tutorial > 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.

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-08-04 09:19:59
Original
1932 people have browsed it

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 '
';
Copy after login
Related labels:
source:php.cn
Statement of this Website
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template