Loop Through Nested Array To Generate Tables Of Different Lengths
I'm trying to show demand for exams of different levels in different locations. I have some code that outputs a series of 4 two-column tables across a page. Each table shows total
Solution 1:
Maybe, this shall help you.
You just need to pay attention at foreach
syntax:
foreach($array as $key => $value)
For example:
$array = array(
"key1" => /*values*/array(
"value1",
"value2"
),
"key2" => /*values*/array(
"value1",
"value2"
)
);
foreach($arrayas$key => $values){
foreach($valuesas$value){
echo"$key => $value\n";
}
}
Will echo:
key1 => value1
key1 => value2
key2 => value1
key2 => value2
So, you code should be:
// Creates arrays $levels = array(
"A1" => array(
'Arlington',
'El Paso',
'White Ridge',
'Jonestown',
'Hochberg'
),
"A2" => array(
'Arlington',
'El Paso',
'Hochberg'
),
"B1" => array(
'El Paso',
'White Ridge',
'Jonestown',
'Hochberg'
),
"B2" => array(
'Arlington',
'El Paso',
'White Ridge'
)
);
// Loop through centres and levels foreach ($levelsas$level => $centres) {
echo'<div id="' . $level . '_column">
<h2 class="' . $level . '">' . $level . '</h2>';
foreach ($centresas$centre) {
// Prepare$stmt1 = $db->prepare("SELECT COUNT(Centre)
FROM exam
WHERE exam.Centre=:centre
AND exam.Level=:level");
$stmt2 = $db->prepare("SELECT COUNT(Centre)
FROM exam
JOIN personal
ON exam.P_ID=personal.P_ID
WHERE personal.Paid='1'
AND exam.Centre=:centre
AND exam.Level=:level");
// Bind $stmt1->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt1->bindParam(':level', $level, PDO::PARAM_STR);
$stmt2->bindParam(':centre', $centre, PDO::PARAM_STR);
$stmt2->bindParam(':level', $level, PDO::PARAM_STR);
// Execute$stmt1->execute();
$stmt2->execute();
// Fetch $row = $stmt1->fetch(PDO::FETCH_ASSOC);
$row2 = $stmt2->fetch(PDO::FETCH_ASSOC);
echo'<table class="Font3White">
<tr class="Title">
<td class="width8">' . $centre . ' > ' . $level . '</td>
<tr>';
if ($row && $row2) {
foreach ($rowas$key => $value) {
echo'<td>';
echo$value;
echo'</td>';
}
foreach ($row2as$key2 => $value2) {
echo'<td> (';
echo$value2;
echo')</td>';
}
echo'</tr>';
}
echo'</table>';
} echo'</div>';
}
Post a Comment for "Loop Through Nested Array To Generate Tables Of Different Lengths"