art
art

Reputation: 313

Create 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
            [id] => 1
        )

    [1] => Array
        (
            [groupNo] => 1002
            [name] => chen
            [id] => 2

        )

    [2] => Array
        (
            [groupNo] => 1002
            [name] => ash
            [id] => 3

        )
    [3] => Array
        (
            [groupNo] => 1001
            [name] => mark
            [id] => 4

        )

)

My current table is like this one :

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

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

Group Number | Name          | ID         |          
-------------+------+---------------------
1001         | James         |    1       |
             +---------------+------------
             | Mark          |    4       |
-------------+----------------------------
1002         | chen          |    2       |
             +----------------------------
             | ash           |    3       |
-------------+----------------------------

Before this, I already try everything and change a lot in my code but still not working to insert number of ID in the right column.

Below is my code :

$newArray = array();

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

    //$sharingcontactTable = '';

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

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

       foreach($val as $key => $td) {
           if($key>0) {
              $sharingcontactTable.= "<tr>";
           }
           $sharingcontactTable .= "<td>{$td}</td>\r\n";
           $sharingcontactTable .= "<td>!! No of ID should in here !!</td>\r\n";
           $sharingcontactTable .= "</tr>\r\n";
       }        
    }
}

Anybody please help me to solve this.

Upvotes: 0

Views: 299

Answers (1)

xdazz
xdazz

Reputation: 160873

Simple fix with:

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

Then in the loop:

       $sharingcontactTable .= "<td>{$td[0]}</td>\r\n";
       $sharingcontactTable .= "<td>{$td[1]}</td>\r\n";

Upvotes: 1

Related Questions