Display key value values ​​of nested arrays in corresponding php html columns

I have data coming in below format in php

'Date 1' =>
  array (
    'Object 1 ' =>
    array (
      'Field 1' => Value 1,
      'Field 2' => Value 2,
      'Field 3' => Value 3,
    ),
  ),
  'Date 2' =>
  array (
    'Object 1 in Date 2' =>
    array (
      'Field 1' => Value 1,
      'Field 2' => Value 2,
    ),
    'Object 2 in Date 2' =>
    array (
      'Field 1' => Value 1,
      'Field 2' => Value 2,
      'Field 3' => Value 3,
    ),
  ),
)

      

I want to display the above data in an HTML table that looks something like this:

Table

I tried using nested foreach loops, but couldn't get the desired result. If I just want to display only the key of one of the arrays, it leaves the other column empty and creates another column for the outgoing values.

Any thoughts would be appreciated.

+3


source to share


1 answer


Hope this helps you:



$result = array(
  'Date 1' =>
  array (
    'Object 1 ' =>
    array (
      'Field 1' => "Value 1",
      'Field 2' => "Value 2",
      'Field 3' => "Value 3",
    ),
  ),
  'Date 2' =>
  array (
    'Object 1 in Date 2' =>
    array (
      'Field 1' => "Value 1",
      'Field 2' => "Value 2",
    ),
    'Object 2 in Date 2' =>
    array (
      'Field 1' => "Value 1",
      'Field 2' => "Value 2",
      'Field 3' => "Value 3",
    ),
  ),
);
function count_childs($parent_array,$total = 0)
{
  if(is_array($parent_array))
  {
    foreach ($parent_array as $key => $value) {
     if(is_array($value)){
        $total += count($value);
        count_childs($value,$total);
     }
     else
        $total += 1;
    }
  }

  return $total;
}
$firstField =false;
$first = false;
echo '<div>';
echo '<table id="r" border=1>';
echo '<tr>';
echo '<th>Date</th>';
echo '<th>Object Type</th>';
 echo '<th>Field</th>';
 echo '<th>Count</th>';
echo '</tr>';
foreach ($result as $key=>$value){
  echo "<tr>";

  $date_rowspan = count_childs($value);
  echo "<td rowspan= $date_rowspan>$key</td>";
  foreach ($value as $key1 => $value1) {
    $obj_rowspan = count_childs($value1);
    echo "<td rowspan= $obj_rowspan>$key1</td>";
    $first_row = true;
    foreach ($value1 as $key2 => $value2) {
      if($first_row){
        echo "<td>$key2</td><td>$value2</td></tr>";
        $first_row = false;
      }
      else
        echo "<td>$key2</td><td>$value2</td><tr>";
    }
  }

  echo "</tr>";
}
echo '</table>';

      

+3


source







All Articles