2009-09-09 3 views
0

계단식 테이블 : 예를 들어인쇄 내가 여기처럼 테이블에 데이터베이스에서 데이터를로드하여 표시하기 위해 노력하고있어

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

의 : 데이터베이스에서

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

내가 두 개의 테이블이 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> 

누군가 k 이런 종류의 테이블을 echo하는 PHP 문장은 무엇입니까?

+0

아직 데이터를 배열이나 개체로 가져 왔습니까? – strager

+0

그건 그렇고, 귀하의 질문에 링크 인증이 필요합니다. 관련 부품을 다른 곳으로 미러링하십시오. – strager

+0

의견을 보내 주셔서 감사합니다! 게시물을 수정 했으므로 이미지를 볼 수 있습니다. 데이터를 배열로 가져 오지 못했지만 문제가되지 않습니다 ...이 대각선 테이블을 인쇄하는 알고리즘을 작성하는 데 도움이 필요합니다. –

답변

1
// 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; 
+0

안녕 Hugh, 감사합니다. 매우 도움이되었다! 환호, Ilija –

1

저는 쿼리 결과를 HTML 테이블로 변환하는 아주 간단한 방법을 사용했습니다. 나는 ... 그 $의 query_result가 참 테스트 및 연관 배열로 결과를 가져

$query_result = mysqli_query($db, $query); 

if ($query_result) { 

    while ($columns = mysqli_fetch_assoc($query_result)) { 

     echo "<tr>\n"; 

     foreach ($columns as $name => $column) { 
      echo "<td>"; 
      printf("%s",$columns[$name]); 
      echo "</td>\n"; 
     } 

     echo "</tr>\n"; 
    } 
} 

편집 : 지금은 내가 정말 응답하지 않은 것을 볼 수 있습니다, 테이블 볼 수있었습니다 너의 질문. 이 쿼리는 분명히 매우 중요합니다. '간단하게 접근하여 결과를 얻을 수있는 쿼리를 어떻게 만들 수 있습니까?'

다른 사람이 몇 가지 아이디어를 갖고 있기를 바랍니다.

+0

해답을 주셔서 감사합니다.하지만 제 질문을 이해하지 못했거나 더 정확하게 말하면 제가 정당한 질문을하지 않았다고 생각합니다. 이것을 확인하십시오 image : http://img196.imageshack.us/img196/1857/cijene.jpg Beograd에서 Novi Sad까지의 가격은 100입니다. Beograd에서 Nis까지의 가격은 200입니다. –

1

이것은 다소 실용적이지만,이 문제를 "올바르게하는 것"에 대한 운동으로 더 다가 가겠습니다.

나는 각 테이블의 간단한 선택을하고 배열에 삽입합니다 : 나는 것 다음 출력

$java_array1 = "var Cities = new Array;\n"; 
foreach($cities as $key=>$city) $java_array1 .= "Cities[$key] = \"$city\";\n"; 
$java_array2 = "var Prices = new Array;\n"; 
foreach($cities as $key=>$price) $java_array2 .= "Prices[$key] = new Array(
                    \"{$price[0]}\", 
                    \"{$price[1]}\", 
                    \"{$price[2]}\", 
                   );\n";

:

$query1 = "SELECT * FROM cities"; 
$query2 = "SELECT * FROM prices"; 

$results1 = mysql_query($query1); 
$results2 = mysql_query($query2); 

while($rows = mysql_fetch_array($results1)) $cities[] = $row['name']; 
while($rows = mysql_fetch_array($results2)) $prices[] = array(
                   $row['city1_id'], 
                   $row['city2_id'], 
                   $row['name'] 
                  ); 

내가 동적으로 두 개의 자바 스크립트 목록을 만들려면이를 사용합니다 각 셀에 대해 신중하게 만들어진 ID가있는 테이블 첫 번째 대답과 비슷한 코드를 사용 하겠지만 각 셀에 "cell-<row>-<col>"이라는 고유 ID를 부여합니다.

마지막으로해야 할 일은 onload 자바 스크립트로 채우고 적절한 페어링을 사용합니다. 내 자바 스크립트는 매우 녹슨이지만, 그것은 다음과 같이 보일 것입니다 (: 의사는 다음 주) :

n = 1; 
for(var i in cities) 
{ 
    // set city names on the diagonal 
    document.getElementById('cell-'&i&'-'&i).innerHTML = names[i]; 
    n = n + 1; 
} 

for(var j in prices) 
{ 
    // use the city IDs in the prices array (see earlier code initializing 
    // prices array) to place the prices 
    document.getElementById('cell-'&prices[1]&'-'&prices[2]).innerHTML = prices[0]; 
}

내가 거의 확실히 자바 스크립트의 일부를 엉망; 자신의 책임하에 사용하십시오.

이것은 위에 주어진 간단한 대답보다 훨씬 복잡하지만이 방법을 사용하면 "이해할 수 있습니다"라고 생각할 수있는 유일한 방법입니다. 기본적으로이 방법을 사용하면 이 어디에 있어야합니까?이되어야하며 이상한 테이블과 이상한 선택에 대해 걱정할 필요가 없습니다.

관련 문제