gpt4 book ai didi

php - 如何在 PHP 中平均划分两个数组?

转载 作者:可可西里 更新时间:2023-11-01 12:50:25 25 4
gpt4 key购买 nike

我试图从两组数组中平均划分数组

例如:

$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];

我尝试过的:

$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
$arrRes = [];

$key = 0;

for($i=0;$i<count($arr1);$i++){
$arrRes[$arr1[$key]][] = $arr2[$i];
$key++;
}

$key2 = 0;
for($k=0;$k<count($arr1);$k++){
$arrRes[$arr1[$key2]][] = $arr2[$key];
$key++;
$key2++;
if ($key == count($arr2)) {
break;
}
}

我希望得到输出:

[
"a" => [1,6,11],
"b" => [2,7,12],
"c" => [3,8,13],
"d" => [4,9],
"e" => [5,10]
]

但我得到的实际输出是:

[
"a" => [1,6],
"b" => [2,7],
"c" => [3,8],
"d" => [4,9],
"e" => [5,10]
]

最佳答案

另一种只使用一个循环的方法(代码中的注释)...

$arr1 = ['a','b','c','d','e'];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];

// Create output array from the keys in $arr1 and an empty array
$arrRes = array_fill_keys($arr1, []);

$outElements = count($arr1);
// Loop over numbers
foreach ( $arr2 as $item => $value ) {
// Add the value to the index based on the current
// index and the corresponding array in $arr1.
// Using $item%$outElements rolls the index over
$arrRes[$arr1[$item%$outElements]][] = $value;
}
print_r($arrRes);

输出...

Array
(
[a] => Array
(
[0] => 1
[1] => 6
[2] => 11
)

[b] => Array
(
[0] => 2
[1] => 7
[2] => 12
)

[c] => Array
(
[0] => 3
[1] => 8
[2] => 13
)

[d] => Array
(
[0] => 4
[1] => 9
)

[e] => Array
(
[0] => 5
[1] => 10
)

)

关于php - 如何在 PHP 中平均划分两个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55598880/

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