Thursday 30 August 2018

PHP - Associative array with 1 key + 2 values ​​in the HTML table

I have an Associative Array with 1 Key and 2 Values Like this:

<?php
// file path
$file = 'input.txt';  // REMEMBER TO MENTION THE CORRECT FILE WITH EXTENSION
// open the file and get the resource handle with errors suppressed
$handle = @fopen($file,'r');  // DONT USE @ while at development since it will suppress     errors
// array to hold our values
$params = array();
if($handle)
{
// if handle is there then file was read successfully
// as long as we aren't at the end of the file
   while(!feof($handle))
   {
       $line = fgets($handle);
       $temp = explode(':',$line);
       $params[$temp[0]][] = $temp[1];
       $params[$temp[0]][] = $temp[2];
   }
   fclose($handle);
   }
?>

The Input.txt contains:
key:Value1:Value2

test1@example.com:1:11
test2@test.com:2:12
test3@test.com:3:13
test4@example.com:4:14

I need to go through the array and display the results in a HTML table like this:
+-----------------------------------------------------+
|                     example.com                     |
+---------------------+------------------+------------+
| test1@example.com   |         1        |      11    |
| test4@example.com   |         4        |      14    |
+---------------------+------------------+------------+
|                     test.com                        |
+---------------------+------------------+------------+
| test3@test.com      |         3        |     13     |
| test2@test.com      |         2        |     12     |
+---------------------+------------------+------------+

How can This Be Done?

If you want the domain as a single value, you should split the domain inside the while-loop from the user first:
$line = fgets($handle);
$temp = explode(':',$line);
$mail = explode('@', $temp[0]);
$params[$mail[1]]             = array();  // Initialize the array first, otherwise
$params[$mail[1]][$mail[0]]   = array();  // this could throw a warning/notice
$params[$mail[1]][$mail[0]][] = $temp[1];
$params[$mail[1]][$mail[0]][] = $temp[2];

Then you can use a foreach loop:
foreach ( $params as $domain => $user) {
    echo $domain;
    foreach ( $user as $mail => $data ) {
        echo $mail . "@" . $domain;
        echo $data[0];
        echo $data[1];
    }
}

This of course needs a little formatting. You can echo an HTML table along with the data:
echo "<table>";
foreach ( $params as $domain => $user) {
    echo "<tr><td colspan=3>" . $domain . "</td></tr>";
    foreach ( $user as $mail => $data ) {
        echo "<tr>";
        echo "<td>" . $mail . "@" . $domain . "</td>";
        echo "<td>" . $data[0] . "</td>";
        echo "<td>" . $data[1] . "</td>";
        echo "</tr>";
    }
}
echo "</table>";

0 comments:

Post a Comment