PHP中的MySQL数组在fetch_array中

时间:2016-06-22 12:25:06

标签: php mysql arrays

我有一个表单,用户可以在其中输入ShopID,从汽车列表中选择多选,以及该组的价格。汽车列表插入数据库,例如" audi,saab,volvo"。

我现在正在尝试显示一个显示所有ShopID,所选车辆和团体价格的表格。理想情况下,这就是表格的样子:

Shop ID    Cars    Price
          audi
1         saab     100
          volvo
--------------------------- (this is a table border)
          saab
2         bmw      200
          ford
          honda

此表显示与所有汽车相关的商店ID和团体价格(而不是购物ID和每辆汽车的价格)。

然而,现在,我正在让所有车辆只显示在一行上,例如:

Shop ID         Cars            Price
1         audi, saab, volvo     100

有没有人知道如何在"汽车"中循环播放数组?并且在保持"商店ID"和"价格"只显示一次和所有这些信息? 目前,我创建此表的代码如下:

<table class="table table-striped">
  <tr>
    <th>ShopID</th>
    <th>Cars</th>
    <th>Price</th>
  </tr>
<?php   
while($row = $result->fetch_array()) {
          $output = '<tr>';
                  $output .= '<td>'.$row['shopID'].'</td>';
                  $output .= '<td>'.$row['cars'].'</td>';
                  $output .= '<td>'.$row['price'].'</td>';
                  $output .= '</tr>';

                  echo $output;
}
?>
</table>

谢谢!

修改 我确实尝试使用explode(),但我遇到了同样的问题,我不知道如何将它们放到自己的线上!

3 个答案:

答案 0 :(得分:2)

使用explode()

while($row = $result->fetch_array()) {
      $output = '<tr>';
              $output .= '<td>'.$row['shopID'].'</td>';
              $car = explode(",",$row['cars']);
              $output .= '<td>';
              foreach($car as $c)
              {
              $output .= $c."</br>";
              }
              $output .='</td>';
              $output .= '<td>'.$row['price'].'</td>';
              $output .= '</tr>';
              echo $output;
 }

使用str_replace()

 while($row = $result->fetch_array()) {
      $output = '<tr>';
              $output .= '<td>'.$row['shopID'].'</td>';
              $cars = str_replace(",", "<br/>", $row['cars']);
              $output .= '<td>'.$cars.'</td>';
              $output .= '<td>'.$row['price'].'</td>';
              $output .= '</tr>';
              echo $output;
 }

答案 1 :(得分:1)

在您的车上使用str_replace()

$cars = str_replace(",", "<br/>", $row['cars']);
$output .= '<td>'.$cars.'</td>';

答案 2 :(得分:1)

您可以使用str_replace修改$row['cars']

$carsMultiLine = str_replace(", ", "<br />", $row['cars']);