计算查询中的值的数量

时间:2016-12-26 13:25:23

标签: php drupal-7

我正在使用Drupal(7),但我在PHP中有一个初学者的问题。

我有一个问题:

$array = array('1','2','3');
$nb_value = db_select('truc', 'tructruc')
      ->fields('truc')
      ->condition('value', $array)
      ->execute()
      ->fetchAll();

我想计算每个值存在多少次(多少'1'等)。

我试试这个,但它不起作用:

foreach ($array as $value) {
    if($value == '1') {
        $nb_1 = count($nb_value);
     }
     if($value == '2') {
         $nb_2 = count($nb_value);
     }
     ...
     print $nb_1
     print $nb_2
     ...

我哪里错了? 而foreach是解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用此代码:

foreach ($array as $value) {
   if($value == '1') {
      $nb_1++;
   }
   if($value == '2') {
      $nb_2++;
   }
}
...
print $nb_1
print nb_2
...

或使用此代码(已优化):

foreach ($array as $value) {
   switch($value){
      case '1':
         $nb_1++;
      break;
      case '2':
          $nb_2++;
      break;
      ...
   }
}
...
print $nb_1
print nb_2
...

您还可以使用SQL命令来计算数据。例如。

<?php
    $servername = "localhost";
    $username = "dbusername";
    $password = "dbpassword";
    $dbname = "dbname";

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "select truc,count(truc) as cnt from tructruc group by truc";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "Count of (".$row["truc"].")  = ".$row["cnt"]."<br>";
        }
    } else {
        echo "0 results";
    }
$conn->close();
?>