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

我有以下格式的数据在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,
    ),
  ),
)

我想在HTML表格中显示以上数据,如下所示:

Table

我尝试使用嵌套的foreach循环,但是无法获得所需的结果.如果我只想显示其中一个数组的键,则将另一列留空,并为处理值创建另一列.

任何想法将不胜感激.

解决方法:

希望这个能对您有所帮助:

$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>';
上一篇:MapSqlParameterSource的使用和DAO层sql语句加列名参数


下一篇:【Spring】Spring整合MyBatis