首页 > 解决方案 > 使用数组填充表格

问题描述

我正在尝试计算提交给摄影比赛的图像数量。我正在使用一个数组(称为 $frequencies)来存储我的查询生成的值。我可以创建一个包含比赛名称和条目数的表格,但看不到如何包含与每个比赛相关的 id。简而言之,我想要 id、比赛名称和计数 - 我可以得到所有这三个,但不能让 id 可以用于将用户引导到特定比赛的链接中)。

我明白了(一切正常,但没有 id):

在此处输入图像描述

...但是想要这个(我想不出如何将 id 放入表中):

在此处输入图像描述

在此处输入图像描述

请参阅下面的查询和数组。

<?php
  $con = mysqli_connect( DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE );
  if ( mysqli_connect_errno() ) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error( $con );
  }
  $frequencies = array();
  $cnt_result = "SELECT entered_images.id AS compID,
competitions.name AS compName, 
COUNT(entered_images.id) AS Freq 
FROM entered_images 
INNER JOIN competitions 
ON competitions.id = entered_images.id 
GROUP BY competitions.name";
  $cnt_Recordset1 = mysqli_query( $con, $cnt_result )or die( mysqli_error( $con ) );
  $row_Recordset1 = mysqli_num_rows( $cnt_Recordset1 );
  if ( $cnt_Recordset1 === false ) {
    trigger_error( mysqli_error( $GLOBALS[ 'con' ] ) );
  }
  while ( $row = mysqli_fetch_row( $cnt_Recordset1 ) ) {
    $frequencies[$row[1]] = $row[2];
  }
  ?>

这按要求工作。这是我将值放入表中的方法:

<table width="95%" border="1" align="center">
  <tbody>
    <tr>
        <td align="center" bgcolor="#F8F2C3"><strong>Competition Name</strong></td>
      <td align="center" bgcolor="#F8F2C3"><strong>Count</strong></td>
    </tr>
    <?php foreach ($frequencies as $name => $count) {?>
    <tr>
      <td><?php echo $name?></td>
      <td align="center"><?php echo $count; ?></td>
    </tr>
    <?php
    }
    ?>
  </tbody>
</table>

标签: phpmultidimensional-arraymysqli

解决方案


应该就像简单地将 ID 添加到表中一样简单,不是吗?我建议直接在结果上使用 foreach 循环以避免双重循环。

$sQuery = "SELECT entered_images.id AS compID,
competitions.name AS compName, 
COUNT(entered_images.id) AS Freq 
FROM entered_images 
INNER JOIN competitions 
ON competitions.id = entered_images.id 
GROUP BY competitions.name";

$result = mysqli_query( $con, $cnt_result )or die( mysqli_error( $con ) );

<table width="95%" border="1" align="center">
  <thead>
    <tr>
        <th align="center" bgcolor="#F8F2C3"><strong>ID</strong></th>
        <th align="center" bgcolor="#F8F2C3"><strong>Competition Name</strong></th>
      <th align="center" bgcolor="#F8F2C3"><strong>Count</strong></th>
    </tr>
  </thead>
  <tbody>
    <?php foreach ($result as $row) {?>
    <tr>
      <td><?php echo $row['compID'] ?></td> 
      <td><?php echo $row['compName']?></td>
      <td align="center"><?php echo $row['Freq']; ?></td>
    </tr>
    <?php
    }
    ?>
  </tbody>
</table>

推荐阅读