格式化mysql数据以输出到表中

时间:2010-05-02 23:02:26

标签: php mysql arrays

在今天早些时候的一个问题之后,给出了答案,将数据读入数组并将其分离为打印车辆类型,然后将每个车辆的数据分开。

<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;    
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
  <?php foreach ($rows as $vehicleData):?>
    <li><?php echo $vehicleData['name'];?></li>
  <?php endforeach ?>
  </ul>
<?php endforeach ?>

这对于我想做的事情来说几乎是完美的但是我需要在进入第二个foreach循环之前从数据库打印出两列,即ford和mondeo。我已经尝试过打印$ rows ['model']以及我能想到的所有其他组合,但这不起作用。任何帮助非常感谢

1 个答案:

答案 0 :(得分:0)

我对你的问题感到有点困惑,但SQL语句中的SELECT *意味着数据库中的每一列都应该作为$ row数组中的key =&gt;值对出现。因此,如果您需要将另一个“列”输出到HTML列表元素<li>中,您只需回显(注意:不是“打印”)该列名作为数组键。因此,如果您需要在名为“model”的列中找到的汽车列类型,您可以这样做:

<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;    
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
  <?php foreach ($rows as $vehicleData):?>
    <li><?php echo $vehicleData['name'];?></li>
    <li><?php echo $vehicleData['model'];?></li>
  <?php endforeach ?>
  </ul>
<?php endforeach ?>

编辑:我仍然不清楚你的问题,但是如果每辆车都有相同的车型,而你只是想在循环所有结果之前抓住它一次,我就是猜测这会做到这一点:

<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";

$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;    
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
  <?php foreach ($rows as $vehicleData):?>
    <li><?php echo $vehicleData['name'];?></li>
    <li><?php echo $vehicleData['model'];?></li>
  <?php endforeach ?>
  </ul>
<?php endforeach ?>