2011-02-15 152 views
0

我想聲明一個數組像$value=array('apple'=>'red', 'mango'=>'yellow'). 現在我想要從數據庫中獲取這個值。 蘋果和紅色。 假設這個色彩被保存在名爲「顏色」的表中,並且在水果表中用color_id保存。 現在如何獲取它們並放入這個數組中。數組聲明

我試圖把代碼放在像數組這樣的括號中(代碼來獲取),但它沒有工作。 有人可以幫忙嗎?

表 - >果(fruit_id,COLOR_ID,fruit_name) 表 - >色(COLOR_ID,COLOR_NAME)

$result=mysql_query("select * from 
fruit_table"); 
while($row=mysql_fetch_array($result)){ 
    $row_color-mysql_fetch_array(mysql_query("select color_name from colors where 
color_id=$row['color_id']")); 
$val[]="$row['fruit_name']=>$row_color[color_name]"; 

} 
$data=implode(",",$val); 
$value=array($data); 

thanxx提前。

+1

您使用的數據庫是? – GWW 2011-02-15 06:40:46

+0

mysql,wamp服務器phpmyadmin – champ 2011-02-15 06:41:42

+0

發表你試過的東西。另外,你正在使用哪個數據庫? – SuperSaiyan 2011-02-15 06:41:57

回答

3

你需要做兩件事。

  1. 執行查詢以從數據庫中獲取所需的信息。
  2. 將查詢結果轉換爲您想要的格式。

下面是一些示例代碼(假設您已經成功連接到數據庫)。

假設我已經在你的數據庫模式做出有:

  • 您使用id作爲兩個表
  • name在主鍵包含顏色/水果名稱領域

如果它們是正確的,它應該工作,否則需要對查詢進行小調整

$result = mysql_query(' 
    SELECT fruits.name as fruit, colors.name as color 
    FROM fruits 
    JOIN colors 
    ON fruits.color_id = color.id'); 

if (!$result) { 
    die(mysql_error()); 
} 

$value = array(); 

while ($row = mysql_fetch_assoc($result)) { 
    $value[$row['fruit']] = $row['color']; 
} 

mysql_free_result($result); 
1

這樣?

$value = array(); 
while ($r = mysql_fetch_array($mySqlQuery)){ 
    $value[$r['fruit_field']] = $r['color_field']; 
} 

MySQL query is not here;希望你已經擁有它。

1

以下是進行以下工作的代碼。 這基本上是關鍵值對在關聯數組

//Assuming the name of the fruits column is fruit_name and color column is color_name 

$value = array(); 
$query = "SELECT * FROM colors as c LEFT JOIN fruits as f ON c.color_id=f.color_id"; 
$result = mysql_query($query); 

if(mysql_num_rows($result) > 0) 
{ 
while($row = mysql_fetch_array($result)) 
{ 
$fruitname = $row['fruit_name']; 
$colorname = $row['color_name']; 
$value['$fruitname'] = $color_name; 
} 
} 

在循環結束時的概念作爲所需的值陣列將具有的值。

謝謝 J