clo3o5 clo3o5 - 11 months ago 58
PHP Question

Creating a table with PHP foreach function

I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.

My professor helped me create this function:

include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']




is only there to make sure it works and it does, it prints out the array when activated.

He then guided me to create the table like this:


<table id="demo">

<?php foreach($new_row as $row):?>

<?php endforeach;?>


<script type="text/javascript">
$(document).ready(function() {

// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...


What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.

I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.

Answer Source

You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:

<?php  foreach($new_row as $country => $rows): ?>
  <?php  foreach($rows as $row): ?>
  <?php endforeach;?>
<?php endforeach;?>

Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here:

If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:

<?php foreach($new_row as $country => $rows): 
  $sum = 0;
  foreach($rows as $row): 
    $sum += $row['Value'];
<?php endforeach;?>