извините за мой плохой английский: здесь я ответил на этот вопрос Как показать данные из базы данных с динамическим размахом строк .Снова позвольте мне попытаться ответить на этот вопрос.Во-первых, чтобы мы не работали над запросом mysql.
MySql Работа:
В запросе mysql вы не запрашивали заказ по.Потому что в реальной жизни нельзя ожидать, что после всех записей о том, записи законопроектов будут там.Например, возьмите следующую вставку:
INSERT INTO test_work(ename, sal)
VALUES("tom", 100),
("bill", 450),
("bill", 100),
("tom", 200),
("bill", 250),
("bill", 400),
("James", 50);
SELECT * FROM test_work;
Результат:
+-------+------+
| ename | sal |
+-------+------+
| tom | 100 |
| bill | 450 |
| bill | 100 |
| tom | 200 |
| bill | 250 |
| bill | 400 |
| James | 50 |
+-------+------+
Таким образом, ваш запрос mysql должен быть упорядочен по имени.Здесь также каждый 1011 * sal должен быть назначен.Итак, наш запрос:
SELECT * FROM emp ORDER BY ename, sal;
CODING:
- Всю задачу мы можем разделить на 3 части.
- Mysql Извлечение и сохранение данных в массиве.
- Расчет диапазона строк
- Печать
MySql Datafetching:
Во время выборки данных с сервера mysql всегда следует пытаться использовать функцию mysql_fetch_assoc вместо mysql_fetch_array.Потому что mysql_fetch_assoc вернет только ename и sal.Но mysql_fetch_array вернет массив с индексами ename, sal, 0, 1.
# connect to mysql server
# and select the database, on which
# we will work.
$conn = mysql_connect('', 'root', '');
$db = mysql_select_db('test');
# Query the data from database.
$query = 'SELECT * FROM test_work ORDER BY ename, sal';
$result = mysql_query($query);
# Intialize the array, which will
# store the fetched data.
$sal = array();
$emp = array();
# Loop over all the fetched data, and save the
# data in array.
while($row = mysql_fetch_assoc($result)) {
array_push($emp, $row['ename']);
array_push($sal, $row['sal']);
}
Расчет диапазона строк:
# Intialize the array, which will store the
# rowspan for the user.
$arr = array();
# loop over all the sal array
for ($i = 0; $i < sizeof($sal); $i++) {
$empName = $emp[$i];
# If there is no array for the employee
# then create a elemnt.
if (!isset($arr[$empName])) {
$arr[$empName] = array();
$arr[$empName]['rowspan'] = 0;
}
$arr[$empName]['printed'] = "no";
# Increment the row span value.
$arr[$empName]['rowspan'] += 1;
}
, когдавы распечатаете массив массива arr, результат будет:
Array
(
[bill] => Array
(
[rowspan] => 4
[printed] => no
)
[James] => Array
(
[rowspan] => 1
[printed] => no
)
[tom] => Array
(
[rowspan] => 2
[printed] => no
)
)
Печать с интервалом строки:
echo "<table cellspacing='0' cellpadding='0'>
<tr>
<th>Ename</th>
<th>Sal</th>
</tr>";
for($i=0; $i < sizeof($sal); $i++) {
$empName = $emp[$i];
echo "<tr>";
# If this row is not printed then print.
# and make the printed value to "yes", so that
# next time it will not printed.
if ($arr[$empName]['printed'] == 'no') {
echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
$arr[$empName]['printed'] = 'yes';
}
echo "<td>".$sal[$i]."</td>";
echo "</tr>";
}
echo "</table>";
Оптимизация кода:
Теперь мы можем объединить вычисление интервала строк и выборку данных MySQL.Потому что при сохранении извлеченных данных в массиве мы можем вычислить размер строки.Итак, наш окончательный код:
<!DOCTYPE html>
<html>
<head>
<style>
table tr td, table tr th{
border: black 1px solid;
padding: 5px;
}
</style>
</head>
<body>
<?php
# connect to mysql server
# and select the database, on which
# we will work.
$conn = mysql_connect('', 'root', '');
$db = mysql_select_db('test');
# Query the data from database.
$query = 'SELECT * FROM test_work ORDER BY ename, sal';
$result = mysql_query($query);
# $arr is array which will be help ful during
# printing
$arr = array();
# Intialize the array, which will
# store the fetched data.
$sal = array();
$emp = array();
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# data saving and rowspan calculation #
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
# Loop over all the fetched data, and save the
# data.
while($row = mysql_fetch_assoc($result)) {
array_push($emp, $row['ename']);
array_push($sal, $row['sal']);
if (!isset($arr[$row['ename']])) {
$arr[$row['ename']]['rowspan'] = 0;
}
$arr[$row['ename']]['printed'] = 'no';
$arr[$row['ename']]['rowspan'] += 1;
}
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# DATA PRINTING #
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%#
echo "<table cellspacing='0' cellpadding='0'>
<tr>
<th>Ename</th>
<th>Sal</th>
</tr>";
for($i=0; $i < sizeof($sal); $i++) {
$empName = $emp[$i];
echo "<tr>";
# If this row is not printed then print.
# and make the printed value to "yes", so that
# next time it will not printed.
if ($arr[$empName]['printed'] == 'no') {
echo "<td rowspan='".$arr[$empName]['rowspan']."'>".$empName."</td>";
$arr[$empName]['printed'] = 'yes';
}
echo "<td>".$sal[$i]."</td>";
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Результат: