So I have two sets of arrays:
$a = [
[
'position' => 0,
'color' => 'violet'
],
[
'position' => 2,
'color' => 'red'
],
[
'position' => 5,
'color' => 'green'
],
];
$b = [
[
'color' => 'yellow'
],
[
'color' => 'orange'
],
[
'color' => 'pink'
],
[
'color' => 'blue'
],
];
And what I want to display from this is something like this:
array(7) {
[0]=>
array(1) {
["color"]=>
string(6) "violet"
}
[1]=>
array(1) {
["color"]=>
string(6) "yellow"
}
[2]=>
array(1) {
["color"]=>
string(3) "red"
}
[3]=>
array(1) {
["color"]=>
string(6) "orange"
}
[4]=>
array(1) {
["color"]=>
string(4) "pink"
}
[5]=>
array(1) {
["color"]=>
string(5) "green"
}
[6]=>
array(1) {
["color"]=>
string(4) "blue"
}
}
I'm currently using array_splice
and it does work but it is very slow whenever there's a lot of data.
array_splice
method:
foreach($a as $val) {
array_splice($b, (int) $val['position'], 0, [['color' => $val['color']]]);
}
So what I want to ask is, is there like a PHP function for this or any other ways just to make it fast?
Any help or suggestions would be appreciated!
Thanks!
This method uses $a to get a "start" with array_column to get [pos => color]
.
Then I loop this array to see if there is a missing key, if there is a missing key add one item from $b, else reformat the array from [post => color]
to [['color' => color]]
$pos = array_column($a, "color", "position");
$count = count($pos) + count($b);
for($i=0; $i<$count-1; $i++){
if(!isset($pos[$i])){
$pos[$i] = array_splice($b, 0, 1);
}else{
$pos[$i] = [$pos[$i]];
}
}
ksort($pos);
var_dump($pos);
Same code but without array_splice.
Using a counter to know what item to pick from $b.
$pos = array_column($a, "color", "position");
$count = count($pos) + count($b);
$j = 0;
for($i=0; $i<$count-1; $i++){
if(!isset($pos[$i])){
$pos[$i] = $b[$j];
$j++;
}else{
$pos[$i] = [$pos[$i]];
}
}
ksort($pos);
var_dump($pos);
But this requires $b to be indexed.