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

时间:2016-04-04 17:36:06

标签: php arrays

I have two array I would like to combine.

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

I want result like this:

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

My current attempt looks like this:

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));

But it doesn't produce the expected output as I want.

3 个答案:

答案 0 :(得分:1)

Try the modulus if you know your a2 size.

$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);

Output:

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

答案 1 :(得分:1)

您可以使用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
)

答案 2 :(得分:0)

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;
}

Demo: https://3v4l.org/mZZlv