计算,突出显示和打印两个阵列之间的重复项

时间:2015-05-15 14:32:56

标签: php arrays

首次在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代码。很抱歉没有让预期结果更清晰!

问题已解决: 感谢大家的帮助,第一次使用这个网站,没想到你们这么快的回复。非常感谢你!

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

假设$ secondary是带有欺骗的那个,你应该采取另一种方式:

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

答案 2 :(得分: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)