格式化ouptut MySQL的数据到一个表(formatting mysql data for o

2019-11-03 13:20发布

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

<?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循环打印出从数据库即福特蒙迪欧和两列。 我试着打印$行[“模型”],所有我能想到的其他组合,但不起作用。 任何帮助非常赞赏

Answer 1:

我有点被你的问题,但SELECT * SQL语句混淆意味着从数据库中的每个列应该是存在的$ row数组中的一个关键=>值对。 所以,如果你需要另一个“栏目,”这里输出到一个HTML列表元素<li>你只不过是回应(注意:不是“打印”),该列名作为数组的关键。 所以,如果你需要在名为“模特”一栏发现该车列的类型,你可以这样做:

<?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 ?>

编辑 :我仍然在你的问题还不清楚,但如果每车具有相同的vehicleType,你只是希望通过所有的结果之前的循环,一旦抓住,我猜这将做到这一点:

<?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 ?>


文章来源: formatting mysql data for ouptut into a table
标签: php mysql arrays