从多维数组中取消设置键

I'm having some troubles unseting a key from an array that is located in another array. This is my current scenario. A product has an options array, which can hold multiple arrays, something like this:

array:2 [
  "product_options" => array:2 [
    "opcija" => "vr1"
    "opcija2" => "vr2"
  ]
  "additional_product_options" => array:2 [
    "dodatno1" => "dd1"
    "dodatno2" => "dd2"
  ]
]

In this situation, I need to delete specific key and its value from one of these two nested arrays: product_options & additional_product_options. So, in order to do this, I created a function which accepts 3 parameters:

  • $product - from where I read options
  • $arrayKey - which is the key name of the nested array (ex: opcija)
  • $groupKey - which is the name of parent array (ex: product_options)

I managed to unset the given key from the nested array, but the problem occurs when I try to modify original $product->options array. This is what I tried so far:

foreach ($product->options as $options){
    unset($options[$arrayKey]);
    //dd($options); Gives the right output without one of the keys
    $product->options[$groupKey] = $options; //Here is where the error occurs
}
$product->save();

So, my idea here was to unset opcija value from product_options array, and then update it with the new $option array, which indeed has this opcija key unset, but I'm given the following error:

间接修改重载属性App \ Product :: $ options具有   没有效果

我还有另一种方法可以做到这一点吗?如果您需要任何其他信息,请告诉我。

评论