首页 > 解决方案 > 在 PHP 的数组中只保留一定数量的重复值

问题描述

我有一个这样的数组:

array
(
  [0] => array(
    'title' => 'pizza',
    'store_id' => 65
  ),
  [1] => array(
    'title' => 'hamburger',
    'store_id' => 65
  ),
  [2] => array(
    'title' => 'sandwich',
    'store_id' => 65
  ),
  [3] => array(
    'title' => 'soda',
    'store_id' => 65
  ),
  [4] => array(
    'title' => 'salad',
    'store_id' => 50
  ),
 )
)

我需要对此进行过滤以仅获取每家商店的 3 件商品。它可以是前 3 次出现。

有什么想法可以解决这个问题吗?

Obs:每个数组中有更多的项目和列。

标签: phparraysfiltering

解决方案


我刚刚根据@Barmar 添加计数器的提示找到了一种方法:

function limit_items($items_array, $counter = 3) {
    $filtered = array();
    $stores_added = array();

    foreach($items_array as $item) {
                    
        $occurrences = array_filter($stores_added, function($store) use($item) {
            return $store == $item['store']['name'];
        });
                    
        if(count($occurrences) < $counter) {
            array_push($stores_added, $item['store']['name']);
            array_push($filtered, $item);
        }
    }

    return $filtered;
}

$stores_array = limit_items_by_store($stores_array, 3);

首先,我将 2 个变量设置为数组。一个用于整个过滤后的数组,另一个用于添加的商店。

在我遍历所有项目然后$occurrences为商店名称设置过滤器之后,我将出现长度与计数器进行比较3。当它没有到达时,将商店名称推送到$stores_added数组并将当前项目推送到$filtered数组。

也许会有更好的方法来做到这一点,但对我来说就像一种魅力。


推荐阅读