2012-10-29 90 views
1

首先,我的問題有點模糊或混亂,因爲我不確定如何將我的問題描述爲具體。我試圖查詢一家Knitting公司的庫存商數據庫(使用PHP的學校項目),但我打算將城市打印爲標題而不是每個庫存信息。僅當變量發生變化時纔打印變量?

這裏是我的時刻:

$sql = "SELECT * FROM mc16korustockists where locale = 'south'"; 
    $result = pg_exec($sql); 
    $nrows = pg_numrows($result); 
    print $nrows; 
    $items = pg_fetch_all($result); 
    print_r($items); 

for ($i=0; $i<$nrows2; $i++) { 
    print "<h2>"; 
     print $items[$i]['city']; 
    print "</h2>"; 

    print $items[$i]['name']; 
    print $items[$i]['address']; 
    print $items[$i]['city']; 
    print $items[$i]['phone']; 

    print "<br />";  
    print "<br />"; 

}

我查詢其中的所有數據的數據庫,該行是裁判,姓名,地址,城市,電話,並執行它。查詢行數,然後使用它來確定循環運行的迭代次數是多少,但我想要的是讓h2標題出現在for($ i = 0;)行之上。

嘗試只是打破我的網頁,這可能是沒有問題的。我想我必須計算「城市」中的條目數量,直到它檢測到更改,然後將標題更改爲我認爲的名稱?或者爲每個名字設置一個變量,但是在一定程度上,我可能會手動執行(我非常懷疑這將是最佳實踐)。呵呵,我會歡迎任何批評我的PHP,因爲我剛剛開始。

謝謝你,如果你需要更多的信息,只要問問!

P.S.我們的班級正在使用PostgreSQL而不是MySQL學習,正如您在標籤中看到的一樣。

+0

很高興地看到用PostgreSQL教學的人。作爲結果,你將會學習更少的壞習慣。儘管如此,請在問題中提及您的PostgreSQL版本。 –

回答

1

這將解決你的問題:

$sql = "SELECT * FROM mc16korustockists where locale = 'south' order by city"; 

... 


$city = ''; 

for ($i=0; $i<$nrows2; $i++) { 
    if($items[$i]['city']!=$city) 
    { 
     print "<h2>"; 
      print $items[$i]['city']; 
     print "</h2>"; 
     $city = $items[$i]['city']; 
    } 
    print $items[$i]['name']; 
    print $items[$i]['address']; 
    print $items[$i]['city']; 
    print $items[$i]['phone']; 

    print "<br />";  
    print "<br />"; 
} 
+0

謝謝!完美的作品。我非常感謝你的幫助。 – Sentry

+1

如果答案是正確的,請標記爲,否則stackoverflow將永遠不會知道您的問題已得到解決。考慮一些有用的投票答案。這有助於其他有類似問題的用戶更輕鬆地找到答案 –

0

看看以前的項目,並檢查它是否是同一個城市 - 如果不是,也沒有以前的項目,新的城市!

0

您只需要跟蹤城市何時發生變化並在發生變化時進行打印。

我儘量保持代碼儘可能類似於您提供的內容,以便您可以看到發生更改的位置。

// store previous city, set to NULL by default so the first city from the result set will always be printed 
// (assuming that the first city from the result set is not null). 

$previous_city = NULL; 

for ($i=0; $i<$nrows2; $i++) { 

    // determine what the city is from the current row 
    // creating a separate variable for this is not really necessary, but helps to make the example clearer 
    $current_city = $items[$i]['city']; 

    // check if current city is different to the one in the previous row 
    if ($previous_city != $current_city) { 
    // city is different, lets print it 
    print "<h2>"; 
     print $items[$i]['city']; 
    print "</h2>"; 
    } 

    print $items[$i]['name']; 
    print $items[$i]['address']; 
    print $items[$i]['city']; 
    print $items[$i]['phone']; 

    print "<br />";  
    print "<br />"; 

    // end of loop, the current city, now becomes the previous city 
    $previous_city = $items[$i]['city']; 

}

請注意,您還需要按城市在你的SQL,使所有從1個城市的項目組合在一起,否則此方法將無法正常工作