max
max

Reputation: 25

remove item from array of objects based on item inside object

I have array of objects, for each objects i have name, category, price and couple other things. and from that array i want to remove objects that has specific category.

public function getCSV()
{
    $contents = Storage::disk('dropbox')->get('InventoryReport.csv');
    $lines = explode(PHP_EOL, $contents);
    $items = array();

    // categories to ignore when importing
    $ignore = ['Misc', 'Soft Drinks', 'Juices', 'Water', 'Snack', 'Energy Drink', 'Tobacco', 'Gum', 'Account Payment'];

    foreach ($lines as $line) 
    {
        $items[] = str_getcsv($line);
    }

    array_shift($items);
    array_pop($items);


    // foreach ($items as $item)
    // {
    //   $i = Item::where('upc', $item[7])->first();


    //       if($i == null)
    //       {
    //             $name = str_slug($item[8], '-');

    //             // $inventory = Item::create(
    //             //     ['upc' => $item[7],
    //             //         'name' => $item[8],
    //             //         'price' => $item[9],
    //             //         'stock' => $item[10],
    //             //         'cost' => $item[11],
    //             //         'category' => $item[2],
    //             //         'slug' => $name
    //             //     ]
    //             // );
    //       }

    // }



}

above is my code. I want to remove all the items in array that has category thats inside $ignore array. before i store it into database.

Upvotes: 0

Views: 62

Answers (1)

trincot
trincot

Reputation: 350881

Replace this:

foreach ($lines as $line) 
{
    $items[] = str_getcsv($line);
}

with:

foreach ($lines as $line) {
    $item = str_getcsv($line);
    if (count($item) > 1 && !in_array($item[2], $ignore)) {
        $items[] = $item;
    }
}

Now $items will only have the items you are looking for.

NB: Review whether the calls of array_shift and array_pop are still needed, depending on what the category was of those two items.

Upvotes: 1

Related Questions