2012-05-04 69 views
0

我得到這個JSON結果從MySQL用下面的PHP查詢:PHP MySQL查詢組由項目

/* grab the posts from the db */ 
$query = "SELECT * FROM ko_timetable"; 
$result = mysql_query($query,$link) or die('Errant query: '.$query); 

/* create one master array of the records */ 
$posts = array(); 

if(mysql_num_rows($result)) { 

while($post = mysql_fetch_assoc($result)) { 
     $posts[] = array('post'=>$post); 
    } 
} 

JSON結果

post =   { 
"CLASS_LEVEL" = "Intro/General"; 
"CLASS_TYPE" = "Muay Thai"; 
"DAY_OF_WEEK" = Sunday; 
ID = 19; 
"ORDER_BY" = 5; 
TIME = "1:00pm - 2:30pm"; 
}; 
} 
{ 
post =   { 
"CLASS_LEVEL" = "General/Intermediate/Advanced"; 
"CLASS_TYPE" = "Muay Thai Spar - Competitive"; 
"DAY_OF_WEEK" = Sunday; 
ID = 27; 
"ORDER_BY" = 5; 
TIME = "6:00pm - 9:00pm"; 
}; 
}, 
{ 
post =   { 
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate"; 
"CLASS_TYPE" = "Fighters Training"; 
"DAY_OF_WEEK" = Monday; 
ID = 1; 
"ORDER_BY" = 1; 
TIME = "9:30am - 11:00pm"; 
}; 

但我怎麼能更改此查詢以「DAY_OF_WEEK」獲得此結果組。見下面的例子,感謝您的幫助:

{ 
Sunday =   { 
"CLASS_LEVEL" = "Intro/General"; 
"CLASS_TYPE" = "Muay Thai"; 
"DAY_OF_WEEK" = Sunday; 
ID = 19; 
"ORDER_BY" = 5; 
TIME = "1:00pm - 2:30pm"; 
}; 
{ 
"CLASS_LEVEL" = "General/Intermediate/Advanced"; 
"CLASS_TYPE" = "Muay Thai Spar - Competitive"; 
"DAY_OF_WEEK" = Sunday; 
ID = 27; 
"ORDER_BY" = 5; 
TIME = "6:00pm - 9:00pm"; 
}; 
}, 
{ 
Monday =   { 
"CLASS_LEVEL" = "Fighters/Advanced/Intermediate"; 
"CLASS_TYPE" = "Fighters Training"; 
"DAY_OF_WEEK" = Monday; 
ID = 1; 
"ORDER_BY" = 1; 
TIME = "9:30am - 11:00pm"; 
}; 

感謝

+0

請不要使用古老的'mysql_ *'函數編寫新代碼。他們不再被維護,社區已經開始[棄用流程](http://news.php.net/php.internals/53799)。相反,您應該瞭解準備好的語句並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/mysqli)。如果你關心學習,[這裏是一個很好的PDO相關教程](http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers)。 –

+0

另外,無論這是什麼,它不是JSON。 –

+0

@Truth,問題是**如何更改此查詢以通過「DAY_OF_WEEK」獲取此結果組?** ... –

回答

2

您可以使用DAY_OF_WEEK因爲這樣數組索引,

while($post = mysql_fetch_assoc($result)) { 
     $posts[$posts["DAY_OF_WEEK"]] = array('post'=>$post); 
    } 

但要記住在這個例子中,你已經顯示數組的索引是日期的名稱,那麼前一個星期天的結果就是這周星期天將被替換,等等。 您也可以使用count變量來避免用重複的名稱來替換鍵,如下所示。

$count = 1; 
while($post = mysql_fetch_assoc($result)) { 
     $posts[$posts["DAY_OF_WEEK"].$count] = array('post'=>$post); 
     $count++; 
    } 
+0

謝謝,是完美的,我怎麼能標記「DAY_OF_WEEK」,因此它顯示DAY =星期一({發佈= .....謝謝 – HernandoZ

+0

你能展示一個例子,你如何讓Json顯示,因爲我沒有得到你的觀點。 –

+0

現在所有修復謝謝... – HernandoZ

1

改變這樣的:

while($post = mysql_fetch_assoc($result)) { 
    $posts[ $post['DAY_OF_WEEK'] ] = $post; 
} 
+1

這將覆蓋重複的DAY_OF_WEEK數組鍵。例如,如果它將$ post添加到$ posts ['sunday'],然後嘗試添加一個也使用星期日的不同帖子,則第一個帖子會被覆蓋。相反,試試:'$ posts [$ post ['DAY_OF_WEEK']] [] = $ post;' –

+0

@ acido69 Cillosis是對的,Cillosis是你登頂你的答案我會接受的,謝謝 – HernandoZ

+0

@cillosis如果你登頂你的答案我我會接受,謝謝 – HernandoZ