gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:09:36 25 4
gpt4 key购买 nike

我有一个 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>';

关于php - 在各自的列中显示嵌套的数组键值php html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45072045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com