php - 在 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:每个数组中有更多的项目和列。
解决方案
我刚刚根据@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
数组。
也许会有更好的方法来做到这一点,但对我来说就像一种魅力。
推荐阅读
- docker - Docker 镜像修剪过滤
- neo4j - 如何使用 apoc.refactor.cloneNodes([nodes], true) 返回创建的关系?
- minecraft - 为什么我的召唤箱子的setblock命令不把我告诉它的物品放进去?
- python - 使用函数登录到网页,然后使用 Selenium 在 Python 中继续我的代码
- rust - Diesel:BoxableExpressions 通用表及其连接?
- python - Python 缩放循环
- c - 如何从使用动态分配创建的数组中删除所有重复项?
- html - 谷歌应用程序脚本中的 HtmlService.createHtmlOutput 是否更改字符串/它做什么/添加
- c++ - 类型 t() 和类型 t 有什么区别?
- javascript - React:如何在 Jest 测试中涵盖动态导入?