art art - 1 month ago 9
PHP Question

How to make html merge rows table using php array

I have the following array that I get from mysql database, after I get all data I should create one table to show all values.

Array

(
[0] => Array
(
[groupNo] => 1001
[name] => james
)

[1] => Array
(
[groupNo] => 1002
[name] => chen
)

[2] => Array
(
[groupNo] => 1002
[name] => ash
)
[3] => Array
(
[groupNo] => 1001
[name] => mark
)

)


My current table is like this one :

Group Number | Name | Action |
-------------+------+---------------------
1001 | James | |
------------+----------------+------------
1002 | chen | |
-------------+---------------+------------
1002 | ash | |
-------------+---------------+------------
1001 | mark | |
-------------+---------------+------------


But what I want is my table look exactly like below :

Group Number | Name | Action |
-------------+------+---------------------
1001 | James | |
+---------------+------------
| Mark | |
-------------+----------------------------
1002 | chen | |
+----------------------------
| ash | |
-------------+----------------------------


Below is my code :

<?php
if (count($sharingGroup) > 0) {
for ($i = 0; $i < count($sharingGroup); $i++) {
$sharingGroupRecord = $sharingGroup[$i];
?>
<tr>
<td>' . $sharingGroupRecord ['groupNo'] .'</td>
<td>' . $sharingGroupRecord ['name'] .'</td>
<td><a name="action" href="#">Action<span>
</span></a>
</tr>


Anybody please help me to solve this.

Answer

First you need to recreate the array

$newArray = array();

foreach($sharingGroup as $item) {
    $newArray[$item['groupNo']][] = $item['name'];
}

it'll produce this:

Array
(
    [1001] => Array
        (
            [0] => james
            [1] => mark
        )

    [1002] => Array
        (
            [0] => chen
            [1] => ash
        )

)

then you loop through the newArray

if (count($newArray) > 0) {

    $html = '';

    foreach($newArray as $key => $val) {
       $html .= "<tr>\r\n";    

       $html .= "<td rowspan='".count($val)."'>{$key}</td>\r\n";

       foreach($val as $key => $td) {
           if($key>0) {
              $html.= "<tr>";
           }
           $html .= "<td>{$td}</td>\r\n";
           $html .= "<td>Action</td>\r\n";
           $html .= "</tr>\r\n";
       }        
    }
}

and you'll get this as a result

Here's the code all in one place

Comments