2013-07-15 34 views
0

我以下列方式將數字存儲在數組中:
467:0
其中467是數字,0是出現次數。

我在做什麼是從數據庫中獲取一串數字,然後查找出現多次的數字,如果他們確實增加了出現次數。
PHP Array Increment

$numberCount = explode(':', $this->_presentationArr); 

    if(in_array($numberprefix . ':' . preg_match('/^\d+$/', $numberCount[1]), $this->_presentationArr)) 
    { 

     $pos = array_search($numberprefix . ':' . preg_match('/^\d+$/', $numberCount[1]), $this->_presentationArr); 
     $tmpArr = explode(':', $this->_presentationArr[$pos]); 
     $tmpArr[1]++; # this does not work 


    } 


的$ tmpArr [1]是需要被incredementet爲每個匹配的數目。有任何想法嗎?

+0

請澄清一下您的問題。 「有任何想法嗎?」是相當含糊的。但有一個問題:爲什麼不只是使用二維數組,並擺脫所有解析的東西?會更快更清晰 – fvu

+0

預計該做什麼?您不是在原始數組中分配或覆蓋任何內容,該增量沒有任何用處。 – elclanrs

+0

我知道它不會覆蓋任何東西,但這並不重要,因爲$ arrPos [1]根本不會改變值。那麼它從0到1,但不是2,等等。 – anonamas

回答

0

我覺得你太過於複雜了。 php數組與C中的數組有點不同,他們的行爲更像是一張地圖。這意味着您可以插入密鑰而不用擔心前一個密鑰是否真的存在。這意味着您可以輕鬆快速地創建頻率圖,如下所示:

$occurrencearray = array() 
// this next line is pseudocode 
while ($fetched = fetchnumber()) { 
    $occurrencearray[$fetched]++; 
} 
// once all numbers loaded you can iterate over your occurrence map 
foreach ($occurrencearray as $key => $value) { 
    printf("Number %d occurs %d times",$key,$value); 
    // or of course reconvert it to "key:value" strings for storing 
}