0

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"
},
]
2
  • new_item IS inside the products array. Not sure what you're looking for? Commented Oct 27, 2017 at 19:06
  • It's hard to understand what exactly you want to get as result as you are getting a perfect result from what you are doing Commented Oct 27, 2017 at 19:11

3 Answers 3

1

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';
}
Sign up to request clarification or add additional context in comments.

Comments

1

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';
}

Comments

-1

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>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.