我在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循环,但无法获得所需的结果。如果我只想显示其中一个数组的键,则将另一列留空,并为继续值创建另一列。
任何想法都会受到赞赏。
答案 0 :(得分:3)
希望这会对你有所帮助:
$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>';