Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display nested array key values in respective columns php html

I have a 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 HTML Table that looks something like this:

Table

I tried using nested foreach loops, however could not get the desired result. If I just want to display only key of one of the arrays it leaves the other column blank and creates another column for proceeding values.

Any thoughts would be appreciated.

like image 780
ikck Avatar asked Sep 13 '26 09:09

ikck


1 Answers

Hope this will help 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>';
like image 69
B. Desai Avatar answered Sep 14 '26 23:09

B. Desai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!