Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to delete from a multidimensional array if addon_id key is not present

I have figured out all of the issues I had with this on my own up until here. So far I got this to work to the point where I am able to save data properly. The only question I have is, how do I remove arrays where addon_id is not present?

I want to remove the last two "addon_price" from an array.

[
  {"addon_id":"7","addon_price":"12"},
  {"addon_id":"8","addon_price":"45"},
  {"addon_id":"9","addon_price":"66"},
  {"addon_price":null}, <- remove
  {"addon_price":null} <- remove
]

This is my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$p = ItemsAddon::where('item_id', $request->item_id)->pluck('addon_id');
    
   if($request->addon_id) {
    
      $addons = [
        'addon_id' => $request->addon_id,
        'addon_price' => $request->addon_price
      ];
    
    
      $values = [];
      foreach($addons as $key => $addon) {
    
         foreach($addon as $subkey => $subvalue) {
    
             $values[$subkey][$key] = $subvalue;
    
         }
    
      }
    
      foreach($values as $vkey => $value) {
    
      $item_addon = new ItemsAddon;
    
         if(!$p->contains($value['addon_id'])) {
    
            $item_addon->item_id = $request->item_id;
            $item_addon->addon_id =  $value['addon_id'];
            $item_addon->addon_price = $value['addon_price'];
                     
            $item_addon->save();
    
         } else {
                      
            $item_addon->where(
            [
               'item_id' => $request->item_id,
               'addon_id' => $value['addon_id'],
            ])->update([
                 'addon_id' => $value['addon_id'],
                 'addon_price' => $value['addon_price'],
            ]);
    
         }
    
    }
    
  }

>Solution :

If you have an array like this

 $a = [
    ["addon_id" => "7", "addon_price" => "12"],
    ["addon_id" => "8", "addon_price" => "45"],
    ["addon_id" => "9", "addon_price" => "66"],
    ["addon_price" => null],
    ["addon_price" => null]
];

then you can filter null values in this way:

$b = collect($a)->filter(function ($r) {
    return isset($r["addon_id"]);
})->toArray();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading