I have a multi dimensional array named $p_result which contains product related data now I want to add another key value element (with key "o_id" and value 4) into it using for each or for loop but so far I have tried this
foreach($p_result as $prod){
$prod['o_id']=4;
}
print_r($p_result);
but its not adding [oid]=>4 into each of the array.print_r($p_result) shows
Array (
[0] => Array ( [p_id] => 7 [quantity] => 122 [unitPrice] => 3 [subTotal] => 366 )
[1] => Array ( [p_id] => 8 [quantity] => 133 [unitPrice] => 5 [subTotal] => 665 )
)
Use as &$prod:
foreach($p_result as &$prod){
$prod['o_id']=4;
}
print_r($p_result);
You can do what you want by using the by reference operator &:
foreach($p_result as &$prod) {
$prod['o_id']=4;
}
The reference operator allows you to access the parent variable because you are actually referring to the original variable.
Occasionally using reference can be problematic, in which case another option is:
foreach($p_result as $index => $prod) {
$p_result[$index]['o_id']=4;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With