2

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

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

函数应该返回:

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

你知道这样的功能吗?

4

3 回答 3

2

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

    <?

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";
}
于 2013-04-29T11:57:26.310 回答
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,

那应该可以正常工作;)

多姆

于 2013-04-29T11:41:29.830 回答
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);
于 2013-04-29T12:26:02.313 回答