2013-07-08 78 views
0

我想表明作爲壓延在什麼特定月份的數據就說明這個月所有的數據。如何將數組與數據庫表匹配?

想,我有數據,我的數據庫..

Jan=124; Jan=243; Jan=354 
Feb=978; Feb=765; Feb=756; 

它可以爲:

Jan,2013 
    124 
    243 
    354 

Feb,2013 
    978 
    765 
    756 

我已經做了這樣的代碼:

<?php 
$q2="select * from calendar"; 
$res2=mysql_query($q2); 
$row2=mysql_fetch_assoc($res2); 
$mnth = array('Jan','Feb'); 
$j= count($mnth); 
for ($i=0; $i<= $j; $i++){ 
    if($row2['month']=='June'){ 
     ?><tr><td><?php 
     echo $row2['month']; ?> , <?php echo $row2['year']; 
     ?></td></tr><tbody><div><?php 

     include("connection.php"); 
     $q1="select * from calendar"; 
     $res=mysql_query($q1); 

     while($row=mysql_fetch_assoc($res)){ 
      ?><tr><td><?php 
      echo $row['dates']; 
      ?></td></tr></tbody></div><?php 
     } 
    } 
} 
+2

你能格式化你的代碼,使它可讀?謝謝!另外,這與JavaScript有什麼關係? –

+0

不要使用'mysql_'函數 - 它們已被棄用。切換到'mysqli_'或PDO。 –

+0

什麼是你的表格結構? –

回答

2

我會重新考慮每當你需要打印HTML標籤時,都會拋出PHP。它使你的代碼難以閱讀。

而且,你正在做一個循環,這是一個壞主意,並期待您的問題完全不必要中的查詢。

您還有一個開放的<tbody>標記在您的循環中,沒有關閉</tbody>標記。

而且,作爲@AleksG在評論中提到的,你不應該使用mysql_*功能,因爲它們已被棄用。我建議切換到PDO。

等方面的答案...

假設你的表結構是這樣的:

+-------+------+-------+ 
| month | year | dates | 
+-------+------+-------+ 
| Jan | 2013 | 124 | 
| Jan | 2013 | 243 | 
| Jan | 2013 | 354 | 
| Feb | 2013 | 978 | 
| Feb | 2013 | 765 | 
| Feb | 2013 | 756 | 
+-------+------+-------+ 

根據您的問題的標題,這將使值到一個數組,用鑰匙是月份和年份,並且是數字「日期」字段中的值:

// replace the below line with your mysql connection string 
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); 
$result = $dbh->query(' 
    SELECT month, year, dates FROM calendar ORDER BY year, month 
'); 

$mnth = array(); 
foreach ($result as $row) { 
    $key = $row['month'] .','. $row['year']; // e.g. 'Jan,2013' 
    // push the new value. The inner array will be created automatically 
    $mnth[$key][] = $row['dates']; 
} 

print_r($mnth); 
/* will look like this: 
Array(
    [Jan,2013] => Array(
     [0] => 124, 
     [1] => 243, 
     [2] => 354 
    ), 
    [Feb,2013] => Array(
     [0] => 978, 
     [1] => 765, 
     [2] => 756 
    ) 
) */ 

但根據您的代碼,它看起來像你想輸出這是一個HTML表格。所以這裏是你如何做到這一點。查詢是相同的,所以這只是取代了循環:

echo '<table>'; 
$current = ''; 
foreach ($result as $row) { 
    // check to see if we've switched to a new month/year 
    $next = $row['month'] .','. $row['year']; 
    if ($current != $next) { 
     // if we have moved to a new month/year, print a new header row 
     echo '<tr><th>'. $next .'</th></tr>'; 
     // and update $current 
     $current = $next; 
    } 

    echo '<tr><td>'. $row['dates'] .'</td></tr>'; 
} 
echo '</table>'; 
+0

很好的答案!雖然個人的意見,我會做:'$電流=($電流= sprintf的( '%S,%d',$行[ '月'],$行[ '年'])!)? $行[ '月']:$行[ '年'];':) – Jimbo

+1

@Jimbo:如果等於或'$行[這將$行[ '月']''分配到'$ current' 'year']'到'$ current'(如果不相等)。但是,簡單的連接有什麼問題?我在使用'sprintf'時沒有意識到優勢嗎?我傾向於避免三元組......他們可能很難遵循。 – Travesty3

+0

當然沒有,因此爲什麼只是意見。不知道爲什麼,但我愛*'sprintf()'和三元組。也許這些年來我已經成爲一名代碼狂潮了...... – Jimbo