简体   繁体   中英

complete a html table with a php array

I am trying to insert row titles to a html table, which is later populated by a php array whose contents is from a MYSQL query.

I've got the code to do everything, except that the row titles are repeating in 4 columns at the beginning of each row and not just displaying $item[1] for the first row, $item[2] for the second row, and so on.

Here is my code:

// query the database
$result = mysql_query($query_getproductbrands);

// cols we are interested in (from the SQL query)

$cols = array(
  'productName',
  'brandName',
  'productDescription',
  'productPrice',
);

$titles = array(
  'Product',
  'Brand',
  'Description',
  'Price',
);

// initialize rotated result using cols
$rotated = array();
foreach($cols as $col) {
  $rotated[$col] = array();
}

// fill rotated array
while(($row = mysql_fetch_assoc($result)) !== false) {
  foreach($cols as $col) {
    $rotated[$col][] = $row[$col];
  }
}

// echo html
echo "<table border=1 width=473>";
echo "<tr>";

echo "</tr>";
foreach($rotated as $col => $values) {
 echo "<tr>";

 foreach($titles as $title) {
    echo "<td> " . htmlentities($title) . "</td>";
 }


 foreach($values as $value) {
    echo "<td> " . htmlentities($value) . "</td>";
  }
  echo "</tr>";
}
echo "</table>";

?>

So this is producing a table containing:

Product Brand Description Price product1 product2 product3

Product Brand Description Price brand1 brand2 brand3

Product Brand Description Price description1 description2 description3

Product Brand Description Price price1 price2 price3

And I would like it to produce a table containing:

Product product1 product2 product3

Brand brand1 brand2 brand3

Description description1 description2 description3

Price price1 price2 price3

I've thought about doing a loop for the first 'title' array, and then the loop for the 'values' array, but this doesn't work.

If I echo $col at the first loop instead, I get just the first value (product) repeated, and I could choose $title[0], but I am not sure how to increment this onto each row and then implement the loop for the remaining data query (values).

Please could someone offer some advice to achieve the desired table?

Move this outside of the foreach loop:

foreach($titles as $title) {
    echo "<td> " . htmlentities($title) . "</td>";
 }

Preferably put it between here:

echo "<tr>";
<-- Put me here.
echo "</tr>";

If I'm understanding correctly that should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM