假设我有五个元素的数组。我需要找到那些经常重复并按顺序排列的那些。
$array = array('one','five','five','five','four');
预期输出为:five
,因为它是最大的相等元素序列。我如何找到这些元素或者比较它们的值,以便我可以计算出哪些元素重复了?
foreach ($array as $element) { #find repeating elements }
答案 0 :(得分:0)
尝试这种方式。我认为这将满足您的需求!
$array = array('one','five','five','five','four');
$counts = array_count_values($array);
$max = 0; $key = '';
foreach($counts as $k=>$v){
if($v > $max)
{
$max = $v;
$key = $k;
}
}
echo $key;
答案 1 :(得分:0)
有点像粗野的方法。有点像kingkero引用。例如:
$array = array('one','one','one','five','five','five','five','five','four','four', 'one','four');
$prev = '';
$sequences = array();
// group them
foreach($array as $value) {
if(!isset($sequences[$value])) {
$sequences[$value][] = 0;
$prev = $value;
}
if($prev == $value) {
$val = array_pop($sequences[$value]) + 1;
$sequences[$value][] = $val;
} else {
$prev = $value;
$sequences[$value][] = 1;
}
}
序列将如下所示:
Array
(
[one] => Array
(
[0] => 3
[1] => 1
)
[five] => Array
(
[0] => 5
)
[four] => Array
(
[0] => 2
[1] => 1
)
)
// identify
$data['key_with_the_most'] = '';
$data['consecutive_pattern'] = 0;
foreach($sequences as $key => $value) {
if(max($value) > $data['consecutive_pattern']) {
$data['consecutive_pattern'] = max($value);
$data['key_with_the_most'] = $key;
}
}
echo '<pre>';
print_r($data);
$data
输出到:
Array
(
[key_with_the_most] => five
[consecutive_pattern] => 5
)
答案 2 :(得分:0)
$array = ['a','b','b','c'];
$counts = array_count_values($array);
arsort($counts);
print key($counts);
输出:
b
答案 3 :(得分:0)
假设输入可以有多个序列且项目数相同:
<?php
$array = ['a','a','b','b','c','b'];
$grouped = [];
$last = null;
$i = 0;
foreach($array as $k => $v) {
if($last !== $v)
$i = $k;
$grouped[$i][] = $last = $v;
}
print_r($grouped);
$counted_groups = array_map('count', $grouped);
arsort($counted_groups);
print_r($counted_groups);
$max_consecutives = [];
$max_occurences = current($counted_groups);
$max_counted_keys = array_keys($counted_groups, $max_occurences);
foreach($max_counted_keys as $counted_groups_key)
$max_consecutives[] =
[
'item' => $array[$counted_groups_key],
'no_repeats' => $max_occurences,
'from_index' => $counted_groups_key
];
print_r($max_consecutives);
输出:
Array
(
[0] => Array
(
[0] => a
[1] => a
)
[2] => Array
(
[0] => b
[1] => b
)
[4] => Array
(
[0] => c
)
[5] => Array
(
[0] => b
)
)
Array
(
[0] => 2
[2] => 2
[4] => 1
[5] => 1
)
Array
(
[0] => Array
(
[item] => a
[no_repeats] => 2
[from_index] => 0
)
[1] => Array
(
[item] => b
[no_repeats] => 2
[from_index] => 2
)
)