在数组中查找连续的重复值

时间:2017-02-14 19:44:39

标签: php arrays

让我解释一下,我有一个这样的数组:

$origen = Array("dog","dog","dog","cat","cat","bear","bear","alien","mouse");

重复连续是:狗(3次) 我真的不知道该怎么做。 我想用array_count_values可以做些什么。

你觉得怎么样?

3 个答案:

答案 0 :(得分:2)

如果跟踪连续重复,

array_count_values不会对此有所帮助。您只需循环遍历数组并将每个值与之前的值进行比较。如果它匹配,请增加你的重复"算上那个词。

$origen = array("dog","dog","dog","cat","cat","bear","bear","alien","mouse");

$previous = null;
$repetitions = array();
foreach ($origen as $word) {
    if ($word == $previous) {
        if (!isset($repetitions[$word])) $repetitions[$word] = 1;
        $repetitions[$word]++;
    } 
    $previous = $word;
}
print_r($repetitions);

输出

Array ( [dog] => 3 [cat] => 2 [bear] => 2 )

您的评论是正确的,之前的方法只有在重复的单词只有一个重复的集合时才有效。如果可以有多套(为什么现在?)我想出了这个:

首先,将单词数组分成子数组,由重复的集合分隔。

$previous = null;
foreach ($origen as $word) {
    if ($word != $previous) {
        if (!empty($set)) $sets[] = $set;
        $set = [$word];
    } else {
        $set[] = $word;
    }
    $previous = $word;
}
if ($set) $sets[] = $set;

然后检查集合并添加具有多个项目的实例(连续重复一个单词。)

foreach ($sets as $set) {
    if (count($set) > 1) {
        $key = reset($set);
        if (!isset($result[$key])) $result[$key] = 0;
        $result[$key] += count($set);
    }
}

答案 1 :(得分:0)

使用preg_match_allarray_combinearray_map函数的解决方案:

$origen = ["dog","dog","dog","cat","cat","bear","bear","alien","mouse"];
$reps = [];
if (preg_match_all("/(\w+) (\\1\s?){1,}/", implode(" ", $origen), $matches)) {
    $reps = array_combine($matches[1], array_map(function($v){
        return count(explode(' ', trim($v)));
    }, $matches[0]));
}

print_r($reps);

输出:

Array
(
    [dog] => 3
    [cat] => 2
    [bear] => 2
)

答案 2 :(得分:0)

我可能不应该为此使用会话变量,但是:

session_start();
session_unset();

$_SESSION["counts"] = Array();

function value_count($s) {
     if (!isset($_SESSION[$s])) {
        $_SESSION[$s] = 1;
    } else {
        $_SESSION[$s] += 1;
    }

    if (!in_array($s, $_SESSION["counts"])) {
        array_push($_SESSION["counts"], $s);
    }

}

$origen = Array("dog","dog","dog","cat","cat","bear","b   ear","alien","mouse");

foreach ($origen as $value) {
    value_count($value);
}

foreach ($_SESSION["counts"] as $item) {
    echo $item . ": " . $_SESSION[$item] . "<br>";
}