DaveByrne DaveByrne - 3 months ago 9
HTML Question

Get PHP Array contents into Table (or DIV)

I am using shell_exec to grab some bash line output. This is returned as text like:

22/tcp open ssh
80/tcp open http
153/tcp closed unknown
443/tcp open https


I then create an array using preg_split using '/\s+/' to split on whitespace and newline, echo'ing the array gets:

Array
(
[0] => 22/tcp
[1] => open
[2] => ssh
[3] => 80/tcp
[4] => open
[5] => http
[6] => 153/tcp
[7] => closed
[8] => unknown
[9] => 443/tcp
[10] => open
[11] => https
)


I would like to be able to put these values into a 3 column table (or even better a collection of DIVs) that expands as the data set expands (so loop for whatever n lines returned from bash output). How do I go about getting the above array into a table/div where the rows in this example would looks something like:

____________________________
| 22/tcp | open | ssh |
| 80/tcp | open | http |
| 153/tcp | closed | unknown |
| 443/tcp | open | https |

Answer

Do a quick for loop:

for ( $i = 0, $len = count($array); $i < $len; $i += 3)
{
    echo '<tr>
              <td>' . $array[$i] . '</td>
              <td>' . $array[$i+1] . '</td>
              <td>' . $array[$i+2] . '</td>
    </tr>';
}

You can see it in action here.

You can also use array_chunk() to get your desired result as well:

foreach ( array_chunk($array, 3) as $chunk )
{
    echo '<tr>
              <td>' . $chunk[0] . '</td>
              <td>' . $chunk[1] . '</td>
              <td>' . $chunk[2] . '</td>
    </tr>';
}

You can see it in action here.

Comments