count等于数组的相邻值

时间:2013-04-29 11:39:45

标签: php arrays count

我正在寻找一个计算数组相邻元素的函数。 这里有一个例子:

Array(A,A,A,B,B,C,A,A,A,C,C…)

函数应返回:

3*A, 2*B, 1*C, 3*A, 2*C,...

你知道这样的任何功能吗?

3 个答案:

答案 0 :(得分:1)

这应该可以解决问题。没有警告,

    <?

function arrayCountAdjacent($array) {
    $adjacentArray = array();
    $lastValue = null;
    $i = 0;
    foreach ($array as $key => $value) {
        if ($lastValue === null || $lastValue != $value) {
            $i++;
            $adjacentArray[$i] = array("value" => $value, "count" => 1);

            $lastValue = $value;
        }
        else {
            $adjacentArray[$i]["count"]++;
        }
    }

    return $adjacentArray;
}

$array = array("A", "A", "A", "B", "B", "C", "A", "A", "A", "C");
var_dump(arrayCountAdjacent($array));

foreach(arrayCountAdjacent($array) as $result)
{
    echo $result['count'] ."*". $result['value']."\n";
}

答案 1 :(得分:0)

这应该这样做,没有通知/警告。

$data = array("A","A","A","B","B","C","A","A","A","C");
foreach($data as $val){
    if(!isset($newarray[$val])){$newarray[$val]=0;}
    $newarray[$val]++;
}
print_r($newarray);

输出

Array ( [A] => 6 [B] => 2 [C] => 2 )

$data = array("A","A","A","B","B","C","A","A","A","C");
foreach($data as $val){
    if(!isset($newarray[$val])){$newarray[$val]=0;}
    $newarray[$val]++;
}

foreach($newarray as $key=>$val){
    echo $val.'*'.$key.', ';
}

输出

6*A, 2*B, 2*C,

这应该可以正常工作;)

的Dom

答案 2 :(得分:0)

$myArray = array('A','A','A','B','B','C','A','A','A','C','C');

$counts = array_reduce(
    array_keys($myArray),
    function (&$counter, $key) use ($myArray) {
        static $last = -1;

        if (($key > 0)  && ($myArray[$key] == $myArray[$key-1])) {
            list($char, $count) = explode('*',$counter[$last]);
            $counter[$last] = $char . '*' . ++$count;
        } else {
            $counter[++$last] = $myArray[$key] . '*1';
        }
        return $counter;
    },
    array()
);

var_dump($counts);