gpt4 book ai didi

php - 打印级联表

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:10 26 4
gpt4 key购买 nike

我正在尝试从数据库加载数据并将其显示在表格中,如下所示:

http://img196.imageshack.us/img196/1857/cijene.jpg

在数据库中我有两个表:

cities (id, name)
prices (id, city1_id, city2_id, price)

例如,4 个城市的打印表格如下所示:

<table>
<tr>
<td>city1</td>
<td> </td>
<td> </td>
<td> </td>
</tr>

<tr>
<td> price_city1-city2</td>
<td>city2</td>
<td> </td>
<td> </td>
</tr>

<tr>
<td> price_city1-city3</td>
<td> price_city2-city3</td>
<td>city3</td>
<td> </td>
</tr>

<tr>
<td> price_city1-city4</td>
<td> price_city2-city4</td>
<td> price_city3-city4</td>
<td>city4</td>
</tr>
</table>

有人知道回显这种表格的 PHP 语句是什么吗?

最佳答案

// This single query gets all required data
// NOTE: this query assumes that your price data is entered
// such that from_city always alphabetically precedes to_city!
$sql =
"SELECT a.name AS from_city, b.name AS to_city, price ".
"FROM prices ".
"INNER JOIN cities AS a ON a.id=prices.city1_id ".
"INNER JOIN cities AS b ON b.id=prices.city2_id";


// connect and do query
$conn = mysql_connect($host, $user, $pass);
mysql_select_db($db, $conn);
$q = mysql_query($sql, $conn);


// Stuff all data into an array for manipulation;
// keep list of all cities mentioned
$price = array();
$cities = array();
while (($res = mysql_fetch_assoc($q)) !== false) {
$from = $res['from_city'];
$cities[ $from ] = true;

$to = $res['to_city'];
$cities[ $to ] = true;

$price[$to][$from] = $res['price'];
}

// Invert to get alphabetical list of cities
$cities = array_keys($cities);
sort($cities);
$num = count($cities);


// some utility functions
function table($rows) {
return '<table>'.join($rows).'</table>';
}
function row($cells) {
return '<tr>'.join($cells).'</tr>';
}
function cell($text) {
$text = (string) $text;
if (strlen($text)==0)
$text = '&nbsp;';
return '<td>'.$text.'</td>';
}


// The data is now in the desired order;
// produce output as HTML table
$rows = array();
for ($to = 0; $to < $num; ++$to) {
$t = $cities[$to];
$cells = array();

for ($from = 0; $from < $to; ++$from) {
$f = $cities[$from];

if isset($price[$t]) && isset($price[$t][$f])
$text = $price[$t][$f];
else
$text = '';

$cells[]= cell($text);
}

$cells[]= cell($t); // add destination-label

for ($from = $to+1; $from < $num; ++$from) // pad to proper number of cells
$cells[]= cell('');

$rows[]= row($cells);
}
$html = table($rows);


// show results!
echo $html;

关于php - 打印级联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1402584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com