gpt4 book ai didi

php - 如果键相同,如何组合两个数组并将其分块

转载 作者:行者123 更新时间:2023-12-02 12:25:45 26 4
gpt4 key购买 nike

我正在使用 Laravel 构建一个应用程序,但我遇到了一个问题,我在 php 中有两个数组:

Array1
(
[0] => 15
[1] => 15
[2] => 16
[3] => 16
[4] => 17
[5] => 17
[6] => 17
[7] => 17
)

Array2
(
[0] => 0
[1] => 1
[2] => 1
[3] => 2
[4] => 0
[5] => 1
[6] => 2
[7] => 3
)

在这种情况下,我不能使用 array_chunk,因为 array2 的值​​是动态的,并且如果我组合它, array1 的键一定不能相同,所以,我如何将它组合成这样:

Array
(
[15] => Array
(
[0] => 0
[1] => 1
)

[16] => Array
(
[0] => 1
[1] => 2
)

[17] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)

)

最佳答案

简单的foreach循环:

$arr1 = [15,15,16,16,17,17,17,17];
$arr2 = [0,1,1,2,0,1,2,3];

$result = [];
foreach($arr1 as $k => $v){
$result[$v][] = $arr2[$k];
}

print_r($result);

输出:

Array
(
[15] => Array
(
[0] => 0
[1] => 1
)

[16] => Array
(
[0] => 1
[1] => 2
)

[17] => Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
)

关于php - 如果键相同,如何组合两个数组并将其分块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45520235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com