HTML-tabelgenerering met behulp van twee geneste lusse in PHP

Laat ons ons tabel vorm met behulp van twee geneste lusse:

php<?php
  echo '<table>';
  foreach ($arr as $row) {
    echo '<tr>';
    foreach ($row as $cell) {
      echo "<td>$cell</td>";
    }
    echo '</tr>';
  }
  echo '</table>';
?>

Hierdie metode is handig omdat dit nie nodig is om elke sel van die tabel afsonderlik uit te skryf nie. Die nadeel van hierdie benadering is egter 'n verlies van beheer.

Beheer kan eger herwin word met behulp van voorwaardes, soos volg:

php<?php
  echo '<table>';
  foreach ($arr as $row) {
    echo '<tr>';
    foreach ($row as $key => $cell) {
      if ($key === 'salary') {
        echo "<td>$cell dollars</td>";
      } else {
        echo "<td>$cell</td>";
      }
    }
    echo '</tr>';
  }
  echo '</table>';
?>

Ons kan ons kode soos volg vereenvoudig:

php<?php
  echo '<table>';
  foreach ($arr as $row) {
    echo '<tr>';
    foreach ($row as $key => $cell) {
      if ($key === 'salary') {
        $cell .= ' dollars';
      }
      
      echo "<td>$cell</td>";
    }
    echo '</tr>';
  }
  echo '</table>';
?>
Задание 1

Die volgende array word gegee:

php<?php
  $products = [
    [
      'name'   => 'product1',
      'price'  => 100,
      'amount' => 5,
    ],
    [
      'name'   => 'product2',
      'price'  => 200,
      'amount' => 6,
    ],
    [
      'name'   => 'product3',
      'price'  => 300,
      'amount' => 7,
    ],
  ];
?>

Vorm daarmee 'n HTML-tabel.