I am trying to limit the table to 10 rows if more than 10 rows are found create a new table. The data is read from JSON. The code looks something like this:
<?php
$json = '{"test1": {
"sub1": [
"1", "2", "3"
],
"sub2": [
"1", "2", "3","4"
],
"sub3": [
"1", "2", "3","4"
],
"sub4": [
"1", "2"
]
}
}';
$results = json_decode($json);
echo '<table>';
foreach ($results->test1 as $key => $jsons) {
foreach ($jsons as $value) {
echo '<tr>';
echo '<td>'.ucwords($key).'</td>';
echo '<td>' . $value . '</td>';
echo '</tr>';
}
}
echo '</table>';
?>
The required output looks something like this:
<table>
<tr>
<td>Sub1</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>2</td>
</tr>
<tr>
<td></td>
<td>3</td>
</tr>
<tr>
<td>Sub2</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>2</td>
</tr>
<tr>
<td></td>
<td>3</td>
</tr>
<tr>
<td></td>
<td>4</td>
</tr>
<tr>
<td>Sub3</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>2</td>
</tr>
<tr>
<td></td>
<td>3</td>
</tr>
</table>
<table>
<tr>
<td>Sub3</td>
<td>4</td>
</tr>
<tr>
<td>Sub4</td>
<td>1</td>
</tr>
<tr>
<td></td>
<td>2</td>
</tr>
</table>
I have used foreach
loop do I have to use for
loop to count the size of the JSON file and limit it to 10 and then continue?
Or is there a better approach?
One approach is to use a boolean header on the flags. Then to cut it use modulo % 10 == 0
. Below is just create a new batch using that.
$results = json_decode($json);
$new_array = array();
$i = 0;
foreach($results->test1 as $k => $value) {
$header = true;
foreach($value as $k2 => $v) {
if($i % 10 == 0 || $header) {
$key_pair = array($k, $v);
} else {
$key_pair = array(null, $v);
}
$i++;
$new_array[] = $key_pair;
$header = false;
}
}
foreach(array_chunk($new_array, 10) as $value) {
echo '<table>';
foreach($value as $tr) {
echo '<tr><td>', implode('</td><td>', $tr), '</td></tr>';
}
echo '</table>';