我有两个数组,比如
$first =
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
$second =
Array
(
[0] => apples
[1] => organges
[2] => bananas
[3] => peaches
)
但是,我想按索引将第二个数组元素推入第一个数组中。喜欢
$result =
Array
(
[0] => 1
[1] => apples
[2] => 2
[3] => organges
[4] => 3
[5] => 4
[6] => peaches
[7] => 5
[8] => 6
)
请在不更改第一个元素的情况下order.help me
发布于 2018-06-09 02:30:10
你可以,做一个简单的循环:
$result = [];
for($i=0; $i < count($first); $i++) {
if(isset($first[$i])){$result[] = $first[$i];}
if(isset($second[$i])){$result[] = $second[$i];}
}
如果您的数组具有可变大小,请先比较它们的大小,然后使用较大的计数执行循环。
编辑:
然后,考虑到您希望保留它们各自的顺序,但随机合并数组,您可以这样扭曲前面的代码:
$result = [];
for($i=0; $i < count($first); $i++) {
if(rand(0,1)) {
if(isset($first[$i])){$result[] = $first[$i];}
if(isset($second[$i])){$result[] = $second[$i];}
} else {
if(isset($second[$i])){$result[] = $second[$i];}
if(isset($first[$i])){$result[] = $first[$i];}
}
}
我承认这是非常奇怪和扭曲的,我相信可以做出更优化的东西(它很快就完成了),但是,问题本身就是奇怪的xD我希望它能有所帮助:)
EDIT 2:
事实上,第一次编辑将只交替A/B,以获得完全随机的解决方案,并仍然遵守两个数组的相应顺序:
$result = [];
$end=count($first) + count($second);
$a=0;
$b=0;
for($i=0; $i < $end; $i++ {
if(rand(0,1)) {
if(isset($first[$a])) {
$result[] = $first[$a];
$a++;
} elseif (isset($second[$b])) {
$result[] = $second[$b];
$b++;
}
} else {
if(isset($second[$b])) {
$result[] = $second[$b];
$b++;
} elseif (isset($first[$a])) {
$result[] = $first[$a];
$a++;
}
}
}
https://stackoverflow.com/questions/50766429
复制相似问题