Reputation: 11
I would like to add values from a $secondArray
to $firstArray
:
$firstArray = [
0 => [
'prodID' => 101,
'enabled' => 1,
],
1 => [
'prodID' => 105,
'enabled' => 0,
],
];
The $secondArray
will always have the same amount of array items and will be in the same order as the $firstArray
:
$secondArray = [34, 99];
This is what I have tried but I keep getting the wrong stockQT
values after the exercise:
foreach ($secondArray as $value) {
foreach ($firstArray as &$firstArray) {
$firstArray['stockQT'] = $value;
}
}
Incorrect Result for a var_dump($firstArray)
:
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 99
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99
I have looked at similar posts but cant seem to get the correct vales after using different suggestions like while()
loops. Below is what I need the $firstArray
to look like:
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 34
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99
Upvotes: 1
Views: 42
Reputation: 79024
You just need one foreach()
using the key since $secondArray
will always have the same amount of array items and will be in the same order as the $firstArray
. Notice the &
to modify the actual value in the array:
foreach($firstArray as $key => &$value) {
$value['stockQT'] = $secondArray[$key];
}
Or alternately loop $secondArray
and use the key to modify $firstArray
:
foreach($secondArray as $key => $value) {
$firstArray[$key]['stockQT'] = $value;
}
Upvotes: 1