【问题标题】:remove item from array of objects based on item inside object根据对象内的项目从对象数组中删除项目
【发布时间】:2018-10-27 01:19:22
【问题描述】:

我有一系列对象,对于每个对象,我都有名称、类别、价格和其他一些东西。并从该数组中删除具有特定类别的对象。

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
    //             //     ]
    //             // );
    //       }

    // }



}

以上是我的代码。我想删除数组中具有 $ignore 数组中的类别的所有项目。在我将其存储到数据库之前。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    替换这个:

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

    与:

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

    现在$items 将只有您要查找的项目。

    注意:查看是否仍需要调用 array_shiftarray_pop,具体取决于这两个项目的类别。

    【讨论】:

    • yes array pop 是需要的,因为最后一行是空的,所以当它获取列表中的最后一项时,它会破坏代码
    • 我在if 中添加了count 条件,以便排除null 项目。那么你不应该再这样做array_pop了。
    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    相关资源
    最近更新 更多