0

I would like to output the values of an array into a HTML table. To do this, I would like to use a second array as a controller to specify which values from the array, and the order in which those values from the array are added to the table.

For example here is my data which in my case data will have come directly from a database. I would like to use this data as an output to the table:

$data = '[{ "name": "Peter", "children": "10" }, { "name": "Jayda", "children": "1" }]';
$data = json_decode($data, true);

in my case this data will have come directly from a database.

I do not want to display all of this data in the HTML table and I also would like to have a final column where I do not display data directly from the table, but rather output the result of a function the name of which is taken from the $controller and it's parameter specified by $data. Here is my controller file:

$dataControl = '[
{"field": "name", "source": "db"},
{"field": "children","source": "db"},
{"field": "moreThanTwoChildren", "source": "dynamic", "dynamic_field": "children" } 
]';
$dataControl = json_decode($dataControl, true);

I then have some PHP to loop through the arrays and display the output. I am able to do this with static values without any problem. In the final column I wish to run a function called moreThanTwoChildren using the 'children' field in data as a parameter.

Here is my code to do this:

function moreThanTwoChildren($children) {

  if (intval($children) > 2) {
    return 'more than 2 children';
  } else {
    return 'less than 2 children';
  }
}

echo '<table border=1>';
  foreach ($data as $value) {
    echo '<tr>';
    foreach ($dataControl as $dataPoint) {
    echo '<td>';
    if ($dataPoint['source'] == 'dynamic') {

      // RUN A FUNCTION WITH THIS NAME:
      $dataPoint['field'];

      // USE THIS AS A PARAMETER FOR THE FUNCTION:
      $value[$dataPoint['dynamic_field']];

      // THIS IS EQUIVALENT TO:
      echo moreThanTwoChildren($value[$dataPoint['dynamic_field']]);


    } else {
    echo $value[$dataPoint['field']];
  }
    echo '</td>';
    }
    echo '</tr>';
  }
  echo '<table>';

As you can see, I am looping through the data and if the 'source' is 'db', I output the data. If it's dynamic, I want to echo the output of a function with the same name as 'field' using 'dynamic_field' as a parameter.

I have tried call the function by constructing a text string, but it hasn't worked. Is what I am trying even possible?

Adam Scot
  • 1,259
  • 2
  • 18
  • 35

0 Answers0