2015-05-15 35 views
6

第一次在stackoverflow上發佈。計數,突出顯示和打印兩個數組之間的重複項

在打印主數組後,我設法突出顯示了第二個數組中的值,但我也想要同時在括號中打印重複的次數。我已經用盡了最後一部分的想法,我陷入了多重循環和其他問題。我會在這裏粘貼現在正在工作的內容。

的代碼:

$main = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
       12, 13, 14, 15, 16, 17, 18, 19, 20); 

$secondary = array(1, 6, 10, 6, 17, 6, 17, 20); 

foreach ($main as $number) 

{ 

if (in_array($number, $secondary)) 

{ 

echo $item; 

// this one is supposed to be highlighted, but the html code disappears on stackoverflow 

/* this is where the number of duplicates should appear in bracket, example: 

highlighted number(number of duplicates) */ 

} 

else 

{ 

echo $item; 

// this one is simple 

} 
} 

預期結果:

1(1),2,3,4,5,6(3),7,8,9,10(1), 11,12,13,14,15,16,17(2),18,19,20(1)

基本上,括號包含的值在第二個數組中找到的次數,除了存在有色,但我不能粘貼HTML代碼出於某種原因。對不起,沒有讓預期的結果更清晰!

問題已解決: 感謝大家的幫助,第一次使用本網站,沒想到你們這麼快速的迴應。非常感謝你 !

+1

能否請您發表您預期的結果.. –

回答

2

你需要先使用array_count_values讓你secondary陣列的計數值。這就是你能獲得儘可能

$main = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20); 

$secondary = array(1, 6, 10, 6, 17, 6, 17, 20); 
$count_values = array_count_values($secondary); 

foreach ($main as $key => $value) { 
    if (in_array($value, $secondary)) { 
     echo $value . "<strong>(" . $count_values[$value] . ")</strong>"; 
     echo (++$key == count($main)) ? '' : ','; 
    } else { 
     echo $value; 
     echo (++$key == count($main)) ? '' : ','; 
    } 
} 

輸出:

1(1),2,3,4,5,6(3),7,8,9,10(1),11 ,12,13,14,15,16,17(2),18,19,20(1)

+0

謝謝你的回答。它解決了我的問題。 –

+0

@LostinCode很高興幫助... –

0

假設$次要是一個與受騙者,你應該去了解它的其他方式:

$dupes = array(); 
foreach($secondary as $number) { 
    if (in_array($number, $main)) { 
     $dupes[$number]++; 
    } 
} 
var_dump($dupes); 
+0

這不是我在找的,但感謝你的幫助。我將編輯我的原始帖子並獲得預期結果。 –

0
<?php 
    $main = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12, 13, 14, 15, 16, 17,18,19,20); 
    $secondary = array(1, 6, 10, 6, 17, 6, 17, 20); 
    $result =array(); 
    foreach($main as $key => $value){ 
     $i=0; 
     foreach($secondary as $key1 => $value1){ 
      if($value == $value1){ 
       $i++; 
      } 
      $result[$value] = $i; 
     } 
    } 
    $resultString =''; 
    foreach($result as $key => $value){ 
    $resultString .=$key.'('.$value.'),' ; 
    } 
    echo trim($resultString,','); 
    ?> 

結果:

1(1),2(0),3(0),4(0),5(0),6(3),7(0),8(0),9(0),10(1),11(0),12(0),13(0),14(0),15(0),16(0),17(2),18(0),19(0),20(1) 
相關問題