php - 打印级联表

标签 php algorithm html-table cascade

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

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/

相关文章:

HTML 表格设置不起作用

php - Jquery,拖拽保存到mysql数据库?

c# - C# yield 语句的实现算法

css - 将此 CSS 样式应用于 gridview

java - 可以从 SHA-1 切换到 SHA-256 吗?

python - K中心算法

jquery - 如何使用jQuery选择表格中的某些内容

php - 检查用户评分是否为最低分

php - 使用 Laravel 5 从原始 SQL 语句获取结果

php - 将 PHP 连接到 MariaDB 数据库时出错