'Is it possible to alter rowspan value on previous <td> base on the next loop?
I'm quite new to php and I am having problems modifying my custom rowspan because of the nature of the code. I'm trying to merge two rows if its the same name. But my condition is in the next loop.
If its the same name to the previous loop even the 'type' is different I want to merge the two.
This is my sample code its a bit complicated on the actual but this is the simplified structure. and I'm quite stuck in this code structure
Sample array:
$gems = array(
0 => array:2[
name: Amber
type: 1
value: 20
],
1 => array:2[
name: Amber
type: 2
value: 30
],
2 => array:2[
name: Amber
type: 2
value: 40
],
3 => array:2[
name: Ruby
type: 1
value: 40
],
);
My php code
$html = '<table>'
$rowspan = 1;
foreach($gems as $index => $gem){
if($index == 0){
$prev_name = 'null';
}
if($gem['name'] == $prev_name){
$match = 1;
} else {
$match = 0;
}
$html .= '<tr>'
if($gem['type'] == 1){
<td rowspan="$rowspan">$gem['name']</td> // I want to add the additional rowspan here
}
if($match != 0){
if($gem['type'] == 2){
<td>$gem['name']</td>
}
}
$html .= '</tr>'
}
$prev_name = $gem['name'];
}
$html = '</table>'
I added a condition if($gem['name'] == $prev_name) if the previous looped name is same to the current loop name it will trigger the condition as matched.
Then I want to either add the $match to the rowspan of the previous name and hide the current. but my problem is how can I add the additional rowspan to the previous? My logic is wrong.
My expected table output is
_________________
| 20
|---------
Amber | 40
|---------
| 30
________|________
Ruby | 40
_________________
Solution 1:[1]
How about first do some pre-processing, before making the table? Something like:
$gemsByName = [];
foreach ($gems as $index => $gem) {
$gemsByName[$gem['name']][] = $gem;
}
Now you have a new array with the gem name as the key and an array of gems as the value. You can now do:
foreach ($gemsByName as $gemName => $gems) {
// first create the table rows containing the details of the gems
$rows = [];
foreach ($gems as $gem) {
$rows[] = '<td>' . $gem['type'] . '</td>' .
'<td>' . $gem['value'] . '</td>';
}
// then add the gem name in front of the first row
$rows[0] = '<td rowspan="' . count($gems) . '">' . $gemName . '</td>' . $rows[0];
// finally collapse the rows into html code
$html .= '<tr>' . implode('</tr><tr>', $rows) . '</tr>';
}
There are many alternative ways of doing this. The main idea is to make life easier for yourself by first determining which gems have the same name. That way you know in advance how many there are with the same name.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KIKO Software |
