在我编写PHP的这些年里,我从来没有遇到过我需要在标准的php变量中加入循环的场合。
原因:我需要通过JSON请求传递此变量。
请参阅下面的我当前的代码。
我在这里做的是编写一个脚本,根据用户要求(例如行数和列数)生成标准HTML表。我需要将所有这些HTML放入变量并通过JSON请求传递变量,然后解码并显示给用户。
任何建议/提示/技巧都将是一个巨大的帮助。
<?php
$trows = 5;
$tcolumns = 7;
echo "<table class='table table-striped table-bordered'>";
echo "<thead>";
echo "<tr>";
for ($th = 0; $th < $tcolumns; $th++){echo '<th>[HEADER]</th>';
};
echo "</tr>";
echo "</thead>";
echo "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){ echo '<tr>';
for ($td = 0; $td < $tcolumns; $td++){echo '<td>[CONTENT]</td>';
};
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
?>
答案 0 :(得分:1)
<?php
$trows = 5;
$tcolumns = 7;
$result = "";
$result .= "<table class='table table-striped table-bordered'>";
$result .= "<thead>";
$result .= "<tr>";
for ($th = 0; $th < $tcolumns; $th++){$result .= '<th>[HEADER]</th>';
};
$result .= "</tr>";
$result .= "</thead>";
$result .= "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){$result .= '<tr>';
for ($td = 0; $td < $tcolumns; $td++){$result .= '<td>[CONTENT]</td>';
};
$result .= "</tr>";
}
$result .= "</tbody>";
$result .= "</table>";
?>
答案 1 :(得分:1)
创建一个变量,比如$output
,将html表存储在。
中
完成表格构建后,您可以随意选择。打印出来,在另一个变量中使用它来构建一个json对象。
见下文
$output = "<table class='table table-striped table-bordered'>";
$output .= "<thead>";
$output .= "<tr>";
for ($th = 0; $th < $tcolumns; $th++){
$output .= '<th>[HEADER]</th>';
};
$output .= "</tr>";
$output .= "</thead>";
$output .= "<tbody>";
for ($tr = 0; $tr < $trows; $tr++){
$output .= '<tr>';
for ($td = 0; $td < $tcolumns; $td++){
$output .= '<td>[CONTENT]</td>';
};
$output .= "</tr>";
}
$output .= "</tbody>";
$output .= "</table>";
echo $output;
答案 2 :(得分:-1)
使用输出缓冲:
// Start output buffering
ob_start();
/*
Your code here
*/
// Fetch buffered output and save to variable
$content = ob_get_contents();
// End output buffering, flush buffer. This outputs the buffer content
ob_end_clean();
// If you don't want the buffer to be output use this
// ob_end_clean();