【问题标题】:Keep just a certain amount of duplicate value in an array in PHP在 PHP 的数组中只保留一定数量的重复值
【发布时间】:2021-07-22 05:59:00
【问题描述】:

我有一个这样的数组:

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:每个数组中有更多的项目和列。

【问题讨论】:

  • 创建一个对象,在其中保存每个商店的商品计数器。当计数器达到 3 时,停止将重复项添加到结果数组中。
  • 感谢您的提示,我找到了基于它的解决方案,并将在此处发布。

标签: php arrays filtering


【解决方案1】:

我刚刚根据@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 数组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-05
    • 2014-06-03
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2014-06-19
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多