0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

yes array pop is needed because last row comes in as null so when it gets last item in list it will break code
I added in the if a count condition so that it will exclude null items. So then you should not do that array_pop any more.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.