2011-12-14 60 views
0

我試着去以下:比較特定號碼的號碼連續

我有一個具體的數字,我想比較連續這個數字到數字,並獲得數每個號碼。

我有一個樣本,其工作正常,但如果行包含3個或更多相同的數字和具體數量只有2個相同的數字,如果具體數目是將計爲3

例如:

和一排有以下數字:

計數SH應該是8 = 1,8 = 1,8 = 0; 2 = 1,5 = 0,6 = 0

因爲只有2中的特定數量的數787-8因此第三8編號不應該在該行中進行計數。

我希望它明確:

這裏是它可能會更清楚地解釋其中的原因:

http://designer121.comze.com/sample.php

回答

1

你可以使用count_chars()在你的具體數量制定出字符,然後橫跨數你行迭代。隨着時間的推移,如果計數大於零,則從特定數字中減去計數或該數字,並且只設置標誌(= 1部分)。

編輯:一些代碼:

$number = '8821270'; 
$rows = '888256'; 
$count = array(); 

$digits = count_chars($number, 1); 

foreach (str_split($rows) as $row) { 
    if (isset($digits[ord($row)]) && $digits[ord($row)] > 0) { 
     $count[] = 1; 
     $digits[ord($row)]--; 
    } else { 
     $count[] = 0; 
    } 
} 

var_dump($count); 
1

如果我理解正確,您從數據庫獲取一個整數,想知道哪些號碼裏面存在預定義的數字。您可以將這些整數轉換爲字符串,而字符串基本上是一個字符數組。因此,首先創建一個數組,其中包含預定義數字中的數字和數量的信息。然後逐個字符地查看數據庫編號,並查看它是否存在於預定義數字的數組中。如果是這樣,請減少該號碼的計數。

的代碼看起來是這樣的:

$number = 8821270; 
$row = 888256; 

//create string representation of integer 
$n = (string)$number; 
//calculate which numbers exist in the $number 
$row_n = array(); 
for($i =0; $i < strlen($n);$i++){ 
    $char = $n[$i]; 
    if (isset($row_n[$char])) { 
     $row_n[$char]++; 
    } 
    else { 
     $row_n[$char] = 1; 
    } 
} 
/* 
    at this point $row_n is an array where the key is a digit from $number 
    and the value is the quantity 
*/ 

//create string representation of fetched number 
$s = (string)$row; 
for($i =0; $i < strlen($s);$i++){ 
    $char = $s[$i]; 

    if (isset($row_n[$char]) && $row_n[$char] > 0) { 
     $result[] = array($char, 1); 
     $row_n[$char]--; //decrease count for that number 
    } 
    else { 
     $result[] = array($char, 1); 
    } 
} 

/* 
    Here result is an array with information on each separate number 
    Right now it looks like this: 
    array 
    0 => array 
     0 => digit 
     1 => status 
    1 => array 
     0 => digit 
     1 => status 

    Modify $result[] = array($char, 1); to make it look whatever you want 

*/ 
+0

感謝我在PHP新,所以我怎麼會顯示結果..? – 2011-12-15 00:10:11

+0

它取決於哪裏。如果你只想看看那裏有什麼,可以使用var_dump($ variable)或print_r($ variable)。如果您想格式化您必須使用 的foreach($結果爲$值){ $位數= $值[0]; $ status = $ value [1];/*在這裏做$數字和$狀態的東西*/ } – Zefiryn 2011-12-15 07:28:48

0

您可以使用array_intersect_assoc,但你必須轉換你的號碼先數組:

$numberOne = '8821270'; 
for($i=0;$i< strlen($numberOne);$i++){ 
    $numberOneArray[] = $numberOne[$i]; 
} 

$numberTwo = '888256'; 
for($i=0;$i< strlen($numberTwo);$i++){ 
    $numberTwoArray[] = $numberTwo[$i]; 
} 

$result = array_intersect_assoc($numberOneArray, $numberTwoArray); 
// display the result 
print_r(array($numberOneArray, $numberTwoArray,$result)); 

由於功能保存鍵,您現在可以尋找連續鍵,從0開始