2013-04-29 68 views
1

我正在尋找一個函數來計算數組的相鄰元素。 這裏一個例子:計數等於數組的相鄰值

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

函數返回:

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

你知道任何這樣的功能呢?

回答

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"; 
} 
+0

謝謝! 並感謝您如此準確地閱讀我的問題。 ;-) – acab 2013-04-29 12:02:15

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

+0

嗯,認爲它應該是'$ newarray [$ VAL] ++',而不是'$ key' ..它是一個數值數組;)。(和我沒有),並將函數名稱更改爲'array_count_values',因爲[array_values](http://php.net/manual/en/function.array-values.php)已經是PHP – dbf 2013-04-29 11:46:04

+0

的內置函數這會給出一個語法錯誤(你不能只重新聲明一個系統函數),如果解決了這個錯誤,會給出一堆警告和輸出Array([0] => 1 [1] => 1 [2] => 1 [3 ] => 1 [4] => 1 [5] => 1 [6] => 1 [7] => 1 [8] => 1 [9] => 1) – nvanesch 2013-04-29 11:48:17

+0

現在修正它,包括輸出。 – Dom 2013-04-29 11:49:29

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);