foreach ($a as $value) {
$result[] = $value;
do {
$bool = rand(0,1) == 1;
$result[] = array_shift($b);
} while ($bool);
}
// insert the remaining of value $b in the $result
foreach ($b as $value)
$result[] = $value;
How to efficiently merge and possibly convolute two arrays?
-
30-06-2022 - |
Pergunta
Suppose, that I have 3 arrays:
$a = [ 1, 2, 3 ]; // victim #1
$b = [ 4, 5, 6, 7, 8]; // victim #2
$result = []; // result
I need to merge $a
and $b
in such order, that each element of $a
array should be followed by element of array $b
. Elements of $b
array, however, might follow each other.
For example:
1 4 2 5 6 3 7 8
I have tried this:
while($a || $b)
{
$bool = rand(1, 100) >= 50;
if($a)
{
$result[] = array_shift($a);
}
if($b)
{
$result[] = array_shift($b);
}
if($bool && $b)
{
$result[] = array_shift($b);
}
}
Which gives desired output:
Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 2
[4] => 6
[5] => 7
[6] => 3
[7] => 8
)
However, I think that it might be inefficient because of array_shift()
s and if()
s appears too much times there.
Question: Is there more efficient way to do that?
P.S.: Thanks, but I do really know how to use array_merge()
. It is not the RTM issue.
Solução
Outras dicas
$a = array(1, 2, 3 ); // victim #1
$b = array( 4, 5, 6, 7, 8); // victim #2
foreach($a as $first)
{
$result[] = $first;
}
foreach($b as $second)
{
$result[] = $second;
}
Alternatively
$a = array(1, 2, 3, 9 ); // victim #1
$b = array( 4, 5, 6, 7, 8); // victim #2
$result = array_merge($a,$b);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow