mafortis
mafortis

Reputation: 7128

Laravel add extra data to array

I have my data like:

data: [,…]
    0: {name: "Product One", price: "15000", quantity: 2, attributes: {attr: {name: "weight", value: "35"}},…}
        attributes: {attr: {name: "weight", value: "35"}}
        conditions: [{name: "blue", value: 0}, {name: "L", value: 0}]
        name: "Product One"
        price: "15000"
        quantity: 2

I need to add id into each array of my data like:

data: [,…]
    0: {name: "Product One", price: "15000", quantity: 2, attributes: {attr: {name: "weight", value: "35"}},…}
        attributes: {attr: {name: "weight", value: "35"}}
        conditions: [{name: "blue", value: 0}, {name: "L", value: 0}]
        name: "Product One"
        price: "15000"
        quantity: 2
        id: 10 // added id

Screenshot

Here is how my database looks like:

one

Code

Currently just getting my cart_data column, need to add column id as well.

$items2 = CartStorage::where('user_id', $user->id)->get();

$items = [];
foreach($items2 as $item){
  $items[] = json_decode($item['cart_data']); 
}

Upvotes: 1

Views: 766

Answers (1)

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

Can be by creating a var and add it there like so:

$items2 = CartStorage::where('user_id', $user->id)->get();

$items = [];
foreach($items2 as $item){
  $decodedItems       = json_decode($item['cart_data'], true);
  $decodedItems['id'] = $item['id'];
  $items[]            = $decodedItems;
}

Upvotes: 2

Related Questions