Reputation: 23
I have a 2d array and a flat array which need to be merged in a special way.
$arr1 = [
['a'],
['b'],
['c'],
['d'],
['e'],
];
$arr2 = ['1', '2'];
Output should be
[
['a', 1],
['b', 2],
['c', 1],
['d', 2],
['e', 1],
]
How do I continuously access the elements of the second array to fill add the new column to the first array?
Upvotes: 0
Views: 90
Reputation: 48070
To recycle items from the second array while populating the new column in the first array, calculate the appropriate element key using the modulus operator. Because access to the preexisting values of the first array are irrelevant, use array destructuring syntax to modify the first array by reference and declare a convenient variable.representing the new column. Demo
$count = count($arr2);
foreach ($arr1 as $i => [1 => &$v]) {
$v = $arr2[$i % $count];
}
var_export($arr1);
Upvotes: 0
Reputation: 14146
This version will allow $arr2
to contain any number of values, should that be a requirement:
<?php
$arr1 = [
['a'], ['b'], ['c'], ['d'], ['e'],
];
$arr2 = ['1', '2'];
// wrap the array in an ArrayIterator and then in an
// InfiniteIterator - this allows you to continually
// loop over the array for as long as necessary
$iterator = new InfiniteIterator(new ArrayIterator($arr2));
$iterator->rewind(); // start at the beginning
// loop over each element by reference
// push the current value in `$arr2` into
// each element etc.
foreach ($arr1 as &$subArray) {
$subArray[] = $iterator->current();
$iterator->next();
}
print_r($arr1);
This yields:
Array
(
[0] => Array
(
[0] => a
[1] => 1
)
[1] => Array
(
[0] => b
[1] => 2
)
[2] => Array
(
[0] => c
[1] => 1
)
[3] => Array
(
[0] => d
[1] => 2
)
[4] => Array
(
[0] => e
[1] => 1
)
)
Hope this helps :)
Upvotes: 1
Reputation: 59701
You can do this with a MultipleIterator
and attach the first array as ArrayIterator
and the second one as InfiniteIterator
, e.g.
<?php
$arr1 = [["a"], ["b"], ["c"], ["d"], ["e"]];
$arr2 = [1,2];
$result = [];
$mIt = new MultipleIterator();
$mIt->attachIterator(new ArrayIterator($arr1));
$mIt->attachIterator(new InfiniteIterator(new ArrayIterator($arr2)));
foreach($mIt as $v)
$result[] = array_merge($v[0], [$v[1]]);
print_r($result);
?>
Upvotes: 2