Laravel php如何遍历数组数组并添加新的键值

时间:2018-08-20 02:29:58

标签: php arrays laravel

这是数组$ optvar的响应形式

    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"}]

我想在每个内部数组中添加sk_id:$ somevalue;

我尝试使用foreach循环,但只有在循环外调用它时才得到最后一个项目;

我的循环:

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 个答案:

答案 0 :(得分:1)

如果我没有误解您的要求,那么它们将对您有用,未经真实数据测试:)

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

print '<pre>';
print_r($optvar);
print '</pre>';

答案 1 :(得分:0)

您可以使用laravel map() eloquent collections

这是laravel示例,

简单数组

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

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

$multiplied->all();

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

用于二维数组

   $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);

输出看起来像

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
    ]
  ]
}

答案 2 :(得分:0)

尝试一下:

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