如何计算php或mysql中相同值的数量

时间:2014-01-13 10:09:09

标签: php mysql

p1  p2  p3  p4  p5          p6           p7       p8
--------------------------------------------------------------------------------------- 
1414    1414    1417    1417    1422,1421   1422,1421   1422,1421     1422,1421

上表有8列,其中相邻列具有相同的值。如何根据php或mysql中的列值计算列数。

例如:

for 1414---values are p1,p2 and count is 2

 for 1422,1421--- values are p5,p6,p7,p8 and count is 4.

任何人都可以帮助我..

阵 (     [0] =>排列         (             [期间] => P1             [subject] => 1434             [nop] => 1         )

<b>
    **[1] => Array
    (
        [period] => p2
        [subject] => 1440,1439
        [nop] => 1
    )
    [2] => Array
    (
        [period] => p2,p3
        [subject] => 1440,1439
        [nop] => 2
    )**
</b>

[3] => Array
    (
        [period] => p2,p3,p4
        [subject] => 1440,1439
        [nop] => 3
    )

[4] => Array
    (
        [period] => p5
        [subject] => 1442
        [nop] => 1
    )

[5] => Array
    (
        [period] => p6
        [subject] => 1442
        [nop] => 1
    )

[6] => Array
    (
        [period] => p7
        [subject] => 1442
        [nop] => 1
    )

我有上面的数组..如何从中删除上面数组中的上述突出显示的值。

2 个答案:

答案 0 :(得分:0)

假设你的$行有表的重复

$your_val = '1414'; // for eg 1414

$result_col = ""; // will contain you columns
$result_count = 0;  // will contain your count

// $row has the each column value when you fetch from database eg $row['p1'] = 1414
foreach($row as $key=>$val)  
{
   if($val==$your_val)
   {
     $result_count += 1;

     if($result_text=="")
     {
      $result_col = $key;
     }
     else
     {
       $result_col = $result_col.",".$key;
     }
   }
}

echo "values are ".$result_col." and count is ".$result_count; // output

答案 1 :(得分:0)

你可以用MySQL做到这一点:

SELECT 
IF(p1='1414',1,0) + IF(p2='1414',1,0)+ IF(p3='1414',1,0) + IF(p4='1414',1,0) + IF(p5='1414',1,0) + IF(p6='1414',1,0) + IF(p7='1414',1,0) + IF(p8='1414',1,0) AS cnt
FROM your_table;

如果您使用PHP访问数据库,则可以用变量替换'1414'来计算变量值的出现次数。