I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_
If the $array1
and $array2
are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
$array1[$index]['Qty'] = $quantity;
}
And it´s done!
If you want to keep the original $array1
untouched, you can make a copy before the foreach.
Create new array and store it there. You can access the value of $array2
because they have the same index of $array1
so you can use the $key
of these two arrays.
$array3 = [];
foreach($array1 as $key => $val) {
$array3[] = [
'id' => $val['id'],
'price' => $val['price'],
'purchase_time' => $val['purchase_time'],
'Qty' => $array2[$key]
];
}
print_r($array3);
Might be a simpler way, but for fun without foreach
:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);
The simplest way is:
$i = 0;
foreach($array1 as &$row) {
$row['Qty'] = $array2[$i++];
}
Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
$row['Qty'] = $array2[$k];
}