0

This is what the array $optvar looks like in response

    0: [{product_id: 18, option_id: 35, value: "green"}, {product_id: 18, option_id: 36, value: "large"}]
    1: [{product_id: 18, option_id: 35, value: "green"}, {product_id: 18, option_id: 36, value: "large"}]

I want to add sk_id: $somevalue in each of the inner array;

I tried using foreach loop but only getting the last item when I call it outside the loop;

my loop:

foreach ($optvar as $innerArray) { 
 if (is_array($innerArray)){

    foreach ($innerArray as $k => &$value) {

         if($value['option_id'] == $option)
         {
            $value['option_id'] =$var[$key]['value'];
         }
           $value['sku_id'] = $sku->id;
           $value['created_at'] = $now;
           $value['updated_at'] = $now;


    } 
 }       

}

3 Answers 3

1

If I don't misunderstood your requirements then they this will work for you, Not tested with real data :)

<?
 foreach($optvar as $index=>$opt){
     foreach($opt as $key => $value)
     {
      $optvar[$index][$key]['sk_id'] = 5;
     }
 }

print '<pre>';
print_r($optvar);
print '</pre>';
Sign up to request clarification or add additional context in comments.

2 Comments

thank you. This works well. Also, is there a way to convert {product_id: 18, option_id: 35, value: "green"} into an associative array?
Have your tried like this way ? json_decode($optvar,1);
1

you can use laravel map() eloquent collections

This is for laravel example,

Simple array

$collection = collect([1, 2, 3, 4, 5]);

$multiplied = $collection->map(function ($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

for two dimentional array

   $collection = collect([
       ['key1' => 'item 1'],
       ['key2' => 'item 2'],
       ['key3' => 'item 3'],
       ['key4' => 'item 4'],
       ['key5' => 'item 5'],

 ]);

$datas = $collection->map(function ($items, $key) {
    $newItem = [];
    foreach ($items as $k => $value) {
        if($k == 0){
            $item = [$k => $value, 'sk_id' => 1];
        }
        else{
            $item = [$k => $value];
        }

       $newItem = $item;
    }
    return $newItem;
});

$datas->all();
dd($datas);

The output looks like.

Collection {#4475 ▼
  #items: array:5 [▼
    0 => array:2 [▼
      "key1" => "item 1"
      "sk_id" => 1
    ]
    1 => array:2 [▼
      "key2" => "item 2"
      "sk_id" => 1
    ]
    2 => array:2 [▼
      "key3" => "item 3"
      "sk_id" => 1
    ]
    3 => array:2 [▼
      "key4" => "item 4"
      "sk_id" => 1
    ]
    4 => array:2 [▼
      "key5" => "item 5"
      "sk_id" => 1
    ]
  ]
}

Comments

0

Try this :

    foreach($outerArray as $key => $array) {
       foreach($array as $key1 => $value) {
          $array[$key1]['sku_id'] = 'XYZ';
       }
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.