2013-05-06 69 views
0

我想解決這個問題。也許這是絕對不正確的,我需要一些幫助。作爲PHP數組的SQL結果

我有這樣的一個表:

INSERT INTO `municipios` (`id`, `provincia`, `municipio`) VALUES (1, 1, 'Alegría-Dulantzi'), (2, 1, 'Amurrio'), (3, 1, 'Añana'), (4, 1, 'Aramaio'), (5, 1, 'Armiñón'), 

這是我的處理程序:

$query = "SELECT * FROM municipios WHERE provincia='1'"; 
$result = mysql_query($query);  
while ($row = mysql_fetch_array($result)) {     
    $groups = array(
    $row{'id'} => array(
     'name' => $row{'municipio'}, 
     'description' => 'Agrupación electoral de ' . $row{'municipio'}, 
     'status' => 'public', 
     'enable_forum' => 1, 
     ), 
     ); 
} 

有了這個,我剛剛得到最後的結果。我嘗試了另一種選擇,但沒有奏效。

+2

不推薦使用我的'mysql_ *'。它被*棄用*,並且不會在更高版本的PHP中被支持。 – christopher 2013-05-06 18:39:47

回答

0

這是你添加groups數組的方式的問題嗎?我認爲每次你設置一個值,你都會覆蓋這個數組。嘗試使用array_push()附加到組。

讓我們知道這有助於!

array_push() http://php.net/manual/en/function.array-push.php

2

像這樣的東西應該解決您的問題:

$groups[] = array(
    $row['id'] => array(
     'name' => $row['municipio'], 
     'description' => 'Agrupación electoral de ' . $row['municipio'], 
     'status' => 'public', 
     'enable_forum' => 1, 
    ), 
); 

但是,我可以建議您使用PDO。有一篇不錯的文章http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/應該讓你朝着正確的方向前進。

+0

非常感謝你的答案......但我之前嘗試過,並沒有工作。這些組已創建,但沒有任何描述,名稱...這是sql表中的結果: INSERT INTO'wp_bp_groups' VALUES(1,1,'','','','', 1,'2013-05-05 08:56:26'); INSERT INTO'wp_bp_groups' VALUES(2,1,'','','','',1,'2013-04-25 02:32:08'); INSERT INTO'wp_bp_groups' VALUES(3,1,'','','','',1,'2013-05-03 22:22:55'); 我會嘗試PDO。再次感謝你。 – 2013-05-06 20:30:28

+0

與PDO同樣麻煩。組已創建,但內部沒有數據。這是我的代碼: $ DBH = new PDO(「mysql:host = $ hostname; dbname = $ dbname」,$ username,$ password); $ STH = $ DBH-> query('SELECT * FROM municipios WHERE provincia = 1'); $ STH-> setFetchMode(PDO :: FETCH_ASSOC); while($ row = $ STH-> fetch()){ $ groups [] = array( $ row ['id'] => array( 'name'=> $ row ['municipio'], 'description'=>'Agrupaciónelectoral de'。$ row ['municipio'], 'status'=>'private', 'enable_forum'=> 1, ), ); } – 2013-05-06 21:00:25

+0

'$ row'的輸出是什麼? – 2013-05-07 13:48:04