Reputation: 190
What I would like to do is the following:
I have an SQL query that give's me an output. On that output 1 make an selection in php.
$cities[$row['stad']][$row['status']]++
This gives me an output like this (within a <pre>
tag ):
Array
(
[Amsterdam] => Array
(
[41] => 2
[21] => 91
[43] => 16
[42] => 2
[20] => 30
[4] => 4
[70] => 3
[84] => 8
[46] => 4
[45] => 5
[999] => 26
[47] => 2
[3] => 8
[44] => 1
[40] => 1
[93] => 5
[56] => 3
[61] => 3
[79] => 3
[48] => 2
[50] => 5
[10] => 10
[52] => 2
[120] => 1
[95] => 1
[1] => 65
[90] => 6
)
I would like to put in an html table like so :
City 41 21 43 42 20 7 …… etc
amsterdam 2 91 16 2 30 4 …… etc
important to know is there are more than 1 city.
This is what I have at the moment :
echo '<table cellpadding="10" cellspacing="10" border="1">';
foreach($cities as $city) {
echo '<tr>';
echo '<td>' . $row['stad'] . '</td>';
echo '<td>' . $city[$row['status']] . '</td>';
echo '</tr>';
}
echo '</table>';
Upvotes: 0
Views: 121
Reputation: 780798
You need another array that lists all the heading values; in my code below I call this array $headings
. This is because the values for each city may have their keys in a different order, and there may be missing keys, so just looping through the city arrays won't get consistent values on each row.
$headings = array(41, 21, 43, 42, 20, 7, etc.);
echo '<table cellpadding="10" cellspacing="10" border="1">';
echo '<tr><th>City</th>';
foreach ($headings as $h) {
echo "<th>$h</th>";
}
echo '</tr>';
foreach($cities as $cityname => $city) {
echo '<tr>';
echo "<td>$cityname</td>";
foreach ($headings as $h) {
echo '<td>' . (isset($city[$h]) ? $city[$h] : '') . '</td>';
}
echo '</tr>';
}
echo '</table>';
Upvotes: 1
Reputation: 9113
Simply use a foreach
on the array to build your table.
<table>
<tbody>
<?php foreach ($cities as $key => $value): ?>
<tr>
<td><?= $key; ?>
<?php foreach ($value as $subkey => $subvalue): ?>
<td><?= $subvalue; ?> </td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
In steps:
Upvotes: 0
Reputation: 81
try this -
<?php
echo '<table cellpadding="10" cellspacing="10" border="1">';
foreach($cities as $city):
foreach($city as $k => $v)
{
echo "<tr><td>$k</td><td>$v</td></tr>";
}
endforeach;
?>
Upvotes: 0
Reputation: 436
use foreach with $key element so you get key directly into it
change this code
foreach($cities as $city) {
echo '<tr>';
echo '<td>' . $row['stad'] . '</td>';
echo '<td>' . $city[$row['status']] . '</td>';
echo '</tr>';
}
to
foreach($cities as $key=> $city) {
echo '<tr>';
echo '<td>' . $key. '</td>';
echo '<td>' . $city . '</td>';
echo '</tr>';
}
Upvotes: 0