简体   繁体   English

在各个列php html中显示嵌套数组键值

[英]Display nested array key values in respective columns php html

I have a data coming in below format in php 我有一个数据以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: 我想在HTML表格中显示上面的数据,如下所示:

Table

I tried using nested foreach loops, however could not get the desired result. 我尝试使用嵌套的foreach循环,但无法获得所需的结果。 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. 任何想法将不胜感激。

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>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM