Skip to content
Advertisement

PHP – Show Array as HTML Table

I have this code which pulls an array of IP and MAC addresses from my server.

<?php
$arpa = shell_exec('arp -a');
$arpa = stristr($arpa, 'Type');
$arpa = preg_replace("/s+/", " ", $arpa);
$arpat = explode(" ", $arpa);

list($k, $v) = each($arpat);

while (list($k, $v) = each($arpat))
{
    $ippp = $v;
    list($k, $v) = each($arpat);
    $iddd = $v;
    list($k, $v) = each($arpat);
    $typer = $v;

    if ($v && $iddd && ($typer != "invalid"))
    {
        if($ippp == "Interface:") break; // only process the first group of IP and MAC addresses
        else $arpa_new_status[$iddd]['ip'] = $ippp;
    }
}

// sort it
//ksort($arpa_new_status);
//reset($arpa_new_status);

foreach ($arpa_new_status as $mac => $values)
{
    $ips_array[] = array("mac" => $mac, "ip" => $values['ip']);
}
?>

This is what it looks like on my browser, ranging from 0 to 20 in this case.

Array Example

Now I’m trying to show the array as a nice HTML table. Any ideas how I can do that using my code structure above?

I started writing some code but it doesn’t work at all and I can’t figure it out. I’m no PHP expert. I’m more of a C/C++ programmer 😛

<table border=1>
    <tr>
        <?php
            $keys = array_keys($ips_array);
            foreach($keys as $key => $value):
            ?>
                <td><?php echo $value;?></td>
            <?php
            endforeach;
        ?>
    </tr>
    <tr>
        <?php
            $data = array_keys($values);
            foreach($data as $key => $mac):
            ?>
                <td><?php echo $value;?></td>
            <?php
            endforeach;
        ?>
    </tr>
</table>

Something like this is what I’m after

Table Example

Thanks.

Advertisement

Answer

<table border=1>
    <tr>
        <td>Mac</td>
        <td>IP</td>
    </tr>
    <?php foreach($ips_array as $ip_data):?>
        <tr>
            <td><?php echo $ip_data['mac'];?></td>
            <td><?php echo $ip_data['ip'];?></td>
        </tr>
    <?php endforeach;?>
</table>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement