[英]Looping two arrays to make html table in php
我有兩個數組,一個用於表標題,第二個用於表數據。
表標題數組
Array
(
[0] => techrepublic.com
[1] => office.microsoft.com
[2] => en.pstrecovery.net
[3] => easeus.com
[4] => download.cnet.com
[5] => datanumen.com
[6] => 2324
)
表數據數組
Array
(
[software services] => Array
(
[datanumen.com] => 2
[office.microsoft.com] => 3
[easeus.com] => 8
[download.cnet.com] => 9
[en.pstrecovery.net] => 10
)
[software services in Delhi] => Array
(
[en.pstrecovery.net] => 1
[datanumen.com] => 3
[office.microsoft.com] => 4
[easeus.com] => 9
[download.cnet.com] => 10
)
[orignal software services] => Array
(
[en.pstrecovery.net] => 1
[easeus.com] => 6
[download.cnet.com] => 7
[datanumen.com] => 8
[office.microsoft.com] => 9
)
)
到現在為止我做了什么
// code for table heading
foreach ( $_POST['competitor']) as $value) { // $_POST['competitor'])
// containts table heading
// array
echo "<th>". $value ."</th>" ;
}
//code for table row
foreach ($details as $Keywords => $comp) { // $details contains row
// data array
echo '<tr><td>' .$Keywords . '</td>';
foreach ($_POST['competitor'] as $competitor) {
if (isset($comp[$competitor])) {
echo '<td>' . $comp[$competitor] . '</td>' ;
} else {
echo '<td>Not Found</td>' ;
}
}
echo '</tr>' ;
}
我無法安排td和tr。 如何實現附件中所示的輸出?
事實是,為了以與標題相同的順序獲取數據,您需要為數據中的每一行再次遍歷標題。 由於您的數據將標頭用作數組鍵,因此這應該很容易。
foreach ( $_POST['competitor'] as $value) {
echo "<th>". htmlspecialchars($value) ."</th>" ;
}
foreach ($details as $Keywords => $comp) {
echo '<tr><td>' . htmlspecialchars($Keywords) . '</td>';
// iterate the headers here instead
foreach ($_POST['competitor'] as $competitor) {
// echo the value for that header from the current row if it's present
if (isset($comp[$competitor])) {
echo '<td>' . htmlspecialchars($comp[$competitor]) . '</td>' ;
} else {
echo '<td>Not Found</td>' ;
}
}
echo '</tr>' ;
}
旁注-不要忘記為HTML輸出正確地轉義字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.