Mysql&;PHP:动态显示矩阵表
我正在尝试使用PHP构建一个矩阵类型的表。MySQL的表结构如下: 表:座位Mysql&;PHP:动态显示矩阵表,php,mysql,Php,Mysql,我正在尝试使用PHP构建一个矩阵类型的表。MySQL的表结构如下: 表:座位 id rows columns value 1 r1 c1 1 2 r2 c2 2 3 r3 c3 3 等等。。n行和列的数量将有,名称也将不同,如a1、a2、b2、b3 我只想显示如下: c1 c2 c3 r1 1 0 0 r2 0 2 0 r3 0 0 3 等等 如何像上面那样显示?使用查询: SELECT
id rows columns value
1 r1 c1 1
2 r2 c2 2
3 r3 c3 3
等等。。n行和列的数量将有,名称也将不同,如a1、a2、b2、b3
我只想显示如下:
c1 c2 c3
r1 1 0 0
r2 0 2 0
r3 0 0 3
等等
如何像上面那样显示?使用查询:
SELECT rows, columns, value
FROM yourTable
ORDER BY rows, columns
然后在循环中处理结果。每当
行
值更改时,在HTML表中启动一个新的
。要添加到Barmar的响应中,最简单的方法是将DB查询的结果视为一个数组,示例如下:
$sql = "Select * from yourtable order by rows, columns";
$results = mysqli->query($sql);
While ($row = $results-> fetch_array()){
$rows[]=$row;
}
Foreach ( $rows as $row){
$row['rows'];
$row['columns'];
}
您将需要修改foreach循环以添加您正在寻找的HTML。此外,mysqli fetch array将在以下链接中进行更详细的讨论:您可以通过数据库中的项目进行循环。 对于每一项,你做一个td,对于每一行,你做一个tr 比如说
<?php
echo "<Table>";
echo "<tr>";
echo "<td></td>";
echo "<td>C1</td>";
echo "<td>C2</td>";
echo "<td>C3</td>";
echo "</tr>";
echo "<tr>";
echo "<td>r1</td>";
echo "<td>1</td>";
echo "<td>0</td>";
echo "<td>0</td>";
echo "</tr>";
echo "<tr>";
echo "<td>r2</td>";
echo "<td>0</td>";
echo "<td>2</td>";
echo "<td>0</td>";
echo "</tr>";
echo "<tr>";
echo "<td>r3</td>";
echo "<td>0</td>";
echo "<td>0</td>";
echo "<td>3</td>";
echo "</tr>";
echo "</table>";
?>
您可以从变量中加载文本,也可以像这样加载mysql文本
<php?
//everything is the same but here is an example of a <td>
$test = "hello world";
echo "<td>".$text."</td>";
?>
这里的想法是将表数组转换为二维矩阵,第一列和第二列是二维矩阵的“键” 现在假设您已经使用SQL从表中获取了数组 以下三个步骤将发挥神奇的作用: 1) 使用表数组列中的键初始化二维矩阵
// Initializing the two dimensional matrix with zeros
function initialize_2d($m, $value = 0) {
$result = array();
for ($i=1; $i <= $m ; $i++) {
for ($j=1; $j <= $m ; $j++) {
$result['r'.$i]['c'.$j] = 0;
}
}
return $result;
}
3) 打印矩阵
// Assign values from Table Structure to Two Dimensional Matrix
function convert_2d($m_arr){
$matrix_arr = initialize_2d(sizeof($m_arr));
foreach($m_arr as $sub_arr)
{
$matrix_arr[$sub_arr[0]][$sub_arr[1]] = $sub_arr[2];
}
return $matrix_arr;
}
// Prints the 2D Matrix
function print_2d($matrix_arr){
$table_html = '';
$table_html .= '<table>
<tr><td></td>';
foreach ($matrix_arr as $matrix_subarr) {
foreach ($matrix_subarr as $key => $value) {
$table_html .= '<td>'.$key.'</td>';
}
break;
}
foreach ($matrix_arr as $key => $matrix_subarr) {
$table_html .= '<tr>
<td>'.$key.'</td>';
foreach ($matrix_subarr as $value) {
$table_html .='<td>'.$value.'</td>';
}
$table_html .= '</tr>';
}
$table_html .= '</table>';
return $table_html;
}
// Array from Table
$m_arr = array(array("r1","c1","1"),array("r2","c2","2"),array("r3","c3","3"));
$matrix_arr = convert_2d($m_arr);
$table_html = print_2d($matrix_arr);
echo $table_html;
<?php
function matrics($int){
$j = $int*$int;
for($i=1;$i<=$j;$i++) {
echo $i.' ';
if($i%$int==0)
echo '<br/>';
}
}
matrics(4);
?>