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

Kam*_*aze 7 php

我正在尝试从两组数组中平均划分数组

例如:

$arr1 = [a,b,c,d,e];
$arr2 = [1,2,3,4,5,6,7,8,9,10,11,12,13];
Run Code Online (Sandbox Code Playgroud)

我尝试过的

$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;
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望得到输出:

[
   "a" => [1,6,11],
   "b" => [2,7,12],
   "c" => [3,8,13],
   "d" => [4,9],
   "e" => [5,10]
]
Run Code Online (Sandbox Code Playgroud)

但是我得到的实际输出是:

[
   "a" => [1,6],
   "b" => [2,7],
   "c" => [3,8],
   "d" => [4,9],
   "e" => [5,10]
]
Run Code Online (Sandbox Code Playgroud)

Nig*_*Ren 7

仅使用1个循环的另一种方式(代码中的注释)...

$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);
Run Code Online (Sandbox Code Playgroud)

输出...

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
        )

)
Run Code Online (Sandbox Code Playgroud)