문제

데이터베이스에서 데이터를로드하고 여기와 같이 테이블에 표시하려고합니다.

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;

다른 팁

쿼리 결과를 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";
    }
}

편집 : 이제 나는 당신의 테이블을 볼 수 있었는데, 당신의 질문에 실제로 대답하지 않았다는 것을 알 수 있습니다. 쿼리는 분명히 매우 중요합니다. 질문은 '단순한 접근 방식으로 테이블로 바꿀 수있는 결과를 반환하는 쿼리를 어떻게 생성합니까?'

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

이것은 다소 실용성의 가장자리에 있지만, 나는 "올바른 일을하는"운동 으로이 문제에 더 접근하고 있습니다.

각 테이블의 간단한 선택을 수행하고 배열에 삽입합니다.

$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']
                                                            );

그런 다음 이것을 사용하여 두 개의 JavaScript 목록을 동적으로 만듭니다.

$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";

다음은 각 셀에 대해 신중하게 제작 된 ID가있는 테이블을 출력합니다. 첫 번째 답변에서 코드와 매우 유사한 코드를 사용하지만 각 셀에 고유 한 ID를 제공합니다. "cell-<row>-<col>".

내가 마지막으로 할 일은 일부를 채울 것입니다 onload 적절한 페어링을 사용하여 테이블을 채우는 JavaScript. 내 JavaScript는 매우 녹슬지 만 다음과 같은 것처럼 보일 것입니다 (참고 : Pseudocode가 따릅니다).

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];
}

나는 그 자바 스크립트 중 일부를 거의 망쳤다. 자신의 위험에 사용하십시오.

이것은 위에서 주어진 단순한 답변보다 훨씬 더 복잡하지만 이것이 "이해하기"를 위해 생각할 수있는 유일한 방법입니다. 기본적 으로이 방법을 사용하면 모든 것을 그 위치에 배치합니다. ~해야 한다 홀수 테이블과 이상한 선택에 대해 걱정할 필요가 없습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top