I have been trying to add a new value pair to an array called products.
This is my array before the loop:
"products": [
{
"id": "050435",
"name": "Test Product",
"price": 10,
}
]
This is my loop:
$item = [];
foreach ($products as $product) {
$item['new_item'] = 'item_value';
}
$products[] = $item;
Now I need to do this as to obtain the 'item_value' I will need to work with the data inside this array to get this value which I can do later. However I get this as a result when I am trying to add this item to this array.
"products": [
{
"id": "050435",
"name": "Test Product",
"price": 10,
},
{
"new_item": "item_value"
}
]
I have tried array_merge and trying $products[0][] etc but I can't get this inside the products array. Any help will be great thanks. This is how I want it to be:
"products": [
{
"id": "050435",
"name": "Test Product",
"price": 10,
"new_item": "item_value"
},
]
It should be that simple:
$products[0]['new_item'] = 'item_value';
If you need this for every product in $products
array then:
foreach ($products as $product) {
$product['new_item'] = 'item_value';
}
If you want to insert new value to product array use this code.
foreach ($products as $product) {
//$item['new_item'] = 'item_value';
$product['new_item'] = 'item_value';
}
You need to loop through the original array of $products
and add a new array-key to each $product
.
$products = [
[
"id"=> "050435",
"name"=> "Test Product",
"price"=> 10
],[
"id"=> "012345",
"name"=> "Test Product 2",
"price"=> 15
]
];
foreach ($products as $product) {
$product['new_item'] = 'item_value';
}
echo "<pre>";
print_r($product);
echo "</pre>";