如何组合两个数组,并重复其中一个直到另一个的长度


How to combine two arrays and repeat one of them until the length of the other?

我有两个数组要合并。

$arr1 = [1, 2, 3, 4, 5, 6, 7, 8];
$arr2 = ['a', 'b', 'c'];

我想要这样的结果:

1 = a
2 = b
3 = c
4 = a
5 = b
6 = c
7 = a
8 = b

我目前的尝试如下:

function array_combine2($arr1, $arr2) {
    $count = min(count($arr1), count($arr2));
    return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}
print_r(array_combine2($arr1,$arr2));

但它并没有产生我想要的预期输出。

如果您知道a2大小,请尝试模数。

$a1 = [1,2,3,4,5,6,7,8];
$a2 = ['a','b','c'];
$a3;
//Hardcoding the modulus value
for ($x = 0; $x < count($a1); $x++) {
    $a3[$x] = $a2[($a1[$x] - 1) % 3];
}
//Dynamic value as per a2 size
for ($x = 0; $x < count($a1); $x++) {
    $a3[$x] = $a2[($a1[$x] - 1) % count($a2)];
}
print_r($a3);

输出:

Array ( [0] => a [1] => b [2] => c [3] => a [4] => b [5] => c [6] => a [7] => b) 

好吧,你可以用MultipleIterator来解决这个问题,只需将这两个数组附加为ArrayIterator,将其中一个添加为InfiniteIterator

代码:

<?php
    $arr1 = [1,2,3,4,5,6,7,8];
    $arr2 = ['a','b','c'];
    $result = [];
    $mIt = new MultipleIterator();
    $mIt->attachIterator(new ArrayIterator($arr1));
    $mIt->attachIterator(new InfiniteIterator(new ArrayIterator($arr2)));
    foreach($mIt as $v)
        $result[$v[0]] = $v[1];
    print_r($result);
?>

输出:

Array (
    [1] => a
    [2] => b
    [3] => c
    [4] => a
    [5] => b
    [6] => c
    [7] => a
    [8] => b
)
function combineThatShit($keys, $values){
    $ret = array();
    $i = 0;
    foreach($keys as $key){
        if(!isset($values[$i])) $i = 0;
        $ret[$key] = $values[$i];
        $i++;
    }
    return $ret;
}

演示:https://3v4l.org/mZZlv