我坚持这些。
this is my array:
$tabel3 = array (
array (
"progdas" => "Java", "sks" => "3", "prior" => "2"
),
array (
"progdas" => "C#", "sks" => "6", "prior" => "1"
),
array (
"mat" => "Dasar", "sks" => "3", "prior" => "1"
),
array (
"mat" => "Lanjut", "sks" => "3", "prior" => "3"
),
);
这是在表格中显示它的代码:
<?php
echo "Tabel 3<br />";
echo "<table width='auto' border='1'>";
//header
echo "
<table width='auto' border='1' >
<tr>
<th colspan='2' scope='col'>Mata Kuliah</th>
<th width='auto' scope='col'>Jumlah SKS</th>
<th width='auto' scope='col'>Prioritas</th>
</tr>
";
foreach ($tabel3 as $rows => $row)
{
//isi
echo "<tr>";
if ($cell == "progdas") {
echo "<th width='auto' rowspan='2' scope='row'>Pemrograman Dasar</th>";
foreach ($row as $col => $cell)
{
echo "<td>" . $cell. "</td>";
}
}
else {
echo "<th width='auto' rowspan='2' scope='row'>Matematika</th>";
foreach ($row as $col => $cell)
{
echo "<td>" . $cell. "</td>";
}
}
echo "</tr>";
}
echo "</table>";
?>
我希望表格看起来像这样:
-----------------------------------------------------
Mata Kuliah | Jumlah SKS | Prioritas |
-----------------------------------------------------
Pemrograman Dasar|_Java___|____________|____________|
_________________|_C#_____|____________|____________|
Matematika |_Dasar__|____________|____________|
_________________|_Lanjut_|____________|____________|
有人知道如何输入数据“Pemrograman Dasar”和“Matematika”吗?我在这段代码中得到了不好的结果。
答案 0 :(得分:2)
首先,您需要重建阵列
foreach ($tabel3 as $row) {
$row_keys = array_keys($row);
$rebuilded[$row_keys[0]][] = $row;
}
在此之后你可以得到下一个数组:
Array (
[progdas] => Array (
[0] => Array ( [progdas] => Java [sks] => 3 [prior] => 2 )
[1] => Array ( [progdas] => C# [sks] => 6 [prior] => 1 )
)
[mat] => Array (
[0] => Array ( [mat] => Dasar [sks] => 3 [prior] => 1 )
[1] => Array ( [mat] => Lanjut [sks] => 3 [prior] => 3 )
)
)
重组后,您可以构建html代码
<?php
echo "Tabel 3<br />";
echo "<table width='auto' border='1'>";
echo "
<table width='auto' border='1' >
<tr>
<th colspan='2' scope='col'>Mata Kuliah</th>
<th width='auto' scope='col'>Jumlah SKS</th>
<th width='auto' scope='col'>Prioritas</th>
</tr>
";
foreach ($rebuilded as $key => $group)
{
echo "<tr><th width='auto' rowspan='".count($group)."' scope='row'>".($key == "progdas" ? "Pemrograman Dasar" : "Matematika")."</th>";
foreach ($group as $row)
{
echo "<td>" . ($key == "progdas" ? $row['progdas'] : $row['mat']). "</td><td>" . $row['sks']. "</td><td>" . $row['prior']. "</td></tr>";
}
}
echo "</table>";
&GT;