Home > Blockchain >  Create table dynamically from array, based on user's choice
Create table dynamically from array, based on user's choice

Time:03-19

I have several arrays with different length, like in my example. The values of the arrays should be displayed in a table, based on a user's choice. Therefore I have several links and the user choice is checked via $_GET.

Because of the different lengths of each Array, the table must be created dynamically. Is there an elegant way to do this?

My idea was to use is like this:

if ($choice=="a") {
   $table= "<tr>" . implode("<td>" . $a . "</td>"). "</tr>";
}

So the table structure would be created based on the arrays length. This way I would need several IF checks. But is there a way that the users choice is calling the right array right way? Likes this:

$table = "<tr>" . implode("<td>" . $choice . "</td>") . "</tr>";

The choice of the user would be a and this is calling the array a???

My example code:

$a = array ("a", "b", "c", "d", "e");
$b = array ("aa", "bb", "cc");
$c = array ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");

$choice = $_GET['choice'];

echo "<a href='?choice=a'>Choice A</a>";
echo "<a href='?choice=b'>Choice B</a>";
echo "<a href='?choice=c'>Choice C</a>";

CodePudding user response:

This is really a question about how to organize your code. I would advise you not to use variable-variables -- even though they are functional, there is almost always a better way to accomplish the same thing that more clearly communicates the intent of your code.

Consider something like this:

function get_data($choice) {
  switch ($choice) {
    case 'a': 
      return array ("a", "b", "c", "d", "e");
      break;
    case 'b':
      return array ("aa", "bb", "cc");
      break;
    // ... etc...
  }
}

$data = get_data($_GET['choice']);

// draw table

CodePudding user response:

Try this solution:

function buildHtmlTable($data)
{
    $cells = "";
    foreach($data as $key => $value){
        $cells .= "<td>$value</td>";
    }

    return "<table>
                <tr>$cells</tr>
            </table>";
}


$a = array ("a", "b", "c", "d", "e");
$b = array ("aa", "bb", "cc");
$c = array ("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg");


$choice = $_GET['choice'];


if( $choice === "a")
    $data = $a;
elseif( $choice === "b")
    $data = $b;
elseif( $choice === "c")
    $data = $c;

$mytable = buildHtmlTable($data);
echo $mytable;
  •  Tags:  
  • php
  • Related