LivinLife
LivinLife

Reputation: 109

How to create a table in html with using a foreach loop in PHP

I'm trying to create a table using a foreach loop in php. I feel like this is a simple fix and I may be over thinking it. I'm able to pull all of the data from a seperate include file but not able to list the columns in the approrpiate column.

I have a separate file that pulls in the below array:

    <?php
     $shop=array(
             'cost'=>array('cd1'=>18, 'cd2'=>11, 'cd3'=>11, 'cd4'=>17, 'cd5'=>21),
             'name'=>array('cd1'=>'Blink 182', 'cd2'=>'George Jones', 'cd3'=>'Sum 41', 'cd4'=>'Filter', 'cd5'=>'Saliva'),
             'quantity'=>array('cd1'=>9, 'cd2'=>8, 'cd3'=>62, 'cd4'=>21, 'cd5'=>41)
             );
      ?>

The below is the code I'm trying to pull the above data into to create a html table:

   <?php
    include('shop.php');
     $headers=$body="";
    $html1 = "<h3>Catalog</h3><table border='1'><tr><th>ID</th>\n";
    foreach($catalog as $key=>$value){ 
  $headers .= "<th>".$key."</th>\n";
  }
   $html2 = "</tr>\n";
  // use a foreach loop to create $body from the data
  $body= "";  
  foreach ($catalog as $key=>$value) {
       foreach ($value as $values){
             $body .= "<tr><td>".$key."</td></tr>\n";
     $body .= "<tr><td>".$values."</td></tr>";  
     }
 }
  echo '</table>';
  $html3 = "</table>";
  $result = $html1.$headers.$html2.$body.$html3; // concatenations for html
     echo $result; 
  ?>

The above keeps listing all values in the first column ID.

Thanks for any tips.

Upvotes: 3

Views: 1944

Answers (1)

Barmar
Barmar

Reputation: 781068

You're looping over the arrays in the wrong order. The outer loop needs to be the rows, but the keys of $catalog are the columns.

$keys = array_keys($catalog);
$first_key = $keys[0];
foreach ($catalog[$first_key] as $id => $value) {
    $body .= "<tr><td>" . $id . "</td>";
    foreach ($keys as $k) {
        $body .= "<td>" . $catalog[$k][$id] . "</td>";
    }
    $body .= "</tr>";
}

The reason this is complicated is because you have your data organized poorly. It would be much better if you grouped all the related information together, instead of having them in separate arrays.

$catalog = array(
    'cd1' => array('name' => 'Blink 182', 'cost' => 18, 'quantity' => 9),
    'cd2' => array('name' => 'George Jones', 'cost' => 11, 'quantity' => 8),
    ...
);

This is the type of structure that your nested loops would work with.

Upvotes: 2

Related Questions