我有一个包含多个整数的数组,我只对重复一定次数的整数感兴趣。例如:
$items = (0, 0, 0, 1, 1, 2, 3, 3, 3)
我想知道哪些项目完全重复$number
(在此示例中为$number = 3
)次(在此示例中为new array $items = (0, 3)
)。
如果没有任何数组项重复$number
次,我需要var $none = 1
。
我知道函数array_count_values但不知道如何将它实现到我的情况......
答案 0 :(得分:3)
$number = 3;
$items = array_keys(array_filter(array_count_values($items), create_function('$n', "return \$n == $number;")));
if (!$items) {
$none = 1;
}
array_count_values
来配置每个号码发生的频率array_filter
回调对此进行过滤,该回调会丢弃所有条目,但计数为$number
$number
次出现的值答案 1 :(得分:1)
我知道有很多解决方案,但我想再增加一个。 ; - )
function array_repeats($items,$repeats,&$none){
$result = array();
foreach (array_unique($items) as $item){
$matches = array_filter($items,create_function('$a','return ($a=='.$item.');'));
if (count($matches) == $repeats)
$result[] = $item;
}
$none = (count($result)?1:0);
return $result;
}
<强> DEMO 强>
答案 2 :(得分:0)
$ repeated_items将是一个仅包含所需项目的数组。
$limit = 3; //your limit for repetition
$catch = array();
foreach ($items as $item){
if(array_key_exists($item, $catch)){
$catch[$item]++;
} else {
$catch[$item] = 1;
}
}
$repeated_items = array();
foreach ($catch as $k=>$caught){
if($caught>=$limit){
$repeated_items[]=$k;
}
}
答案 3 :(得分:0)
一些伪代码可以帮助您入门:
Sort your array in order to get similar items together
Foreach item
if current item == previous item then
repeat count ++
else
if repeat count > limit then
add current item to new array
答案 4 :(得分:0)
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$count = array_count_values($items);
$number = 3;
$none = 1;
$result = array();
foreach(array_unique($items) as $item) {
if($count[$item] == $number) {
$result[] = $item;
$none = 0;
}
}
答案 5 :(得分:0)
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$none=1;
$new_array=array();
$n=3;
dojob($items,$n,$none,$new_array);
function dojob($items,$n,&$none,&$new_array)
{
$values_count=array_count_values($items);
foreach($values_count as $value => $count)
{
if($count ==$n)
{
$none=0;
$new_array[]=$value;
}
}
}
答案 6 :(得分:0)
有点晚了,但是:
<?php
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$temp = array_unique($items);
$result = array();
$none = 1;
$number = 3;
foreach($temp as $tmp)
{
if(count(array_keys($items, $tmp)) == $number)
{
array_push($result,$tmp);
$none = 0;
}
}
print_r($result);
?>
答案 7 :(得分:0)
一种方法是创建一种哈希表并循环遍历数组中的每个项目。
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$number = 3;
$none = 1;
foreach ($items as $value) {
if ($hash[$value] >= $number) {
# This $value has occured as least $number times. Lets save it.
$filtered_items[] = $value;
# We have at least one item in the $items array >= $number times
# so set $none to 0
$none = 0;
# No need to keep adding
continue;
} else {
# Increment the count of each value
$hash[$value]++;
}
}
$items = $filtered_items;
答案 8 :(得分:0)
$items = array(0, 0, 0, 1, 1, 2, 3, 3, 3);
$icnt = array_count_values($items);
function eq3($v) {
return $v==3;
}
var_export(array_filter($icnt, 'eq3'));
将生成array ( 0 => 3, 3 => 3, )
。在你的例子中,0和3重复3次。这里需要Array_filter,实际上,过滤生成的数组并删除必要的值,但你在这里使用array_count_values是正确的。