[英]How do I combine two arrays, one as a key and the other as an array?
[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.