2011-02-16 141 views
0

我有一個包含以下內容的數據庫表:PHP - 幫助建立循環來構建多陣列

id user_id  plant_id  date   value 
68 68   109    2011, 04, 02 300 
67 68   109    2011, 02, 16 300 
66 68   109    2011, 06, 11 120 
65 68   109    2011, 02, 04 120 
64 68   109    2010, 12, 19 55 
63 68   109    2011, 01, 22 456 

62 68   108    2011, 01, 22 888 
61 68   108    2011, 01, 15 123 

我需要創建USER_ID 68被鎖定到plant_id,看起來像這樣的數組:

Array 
(
    [109] => Array 
     (
      [2011, 04, 02] => 300 
      [2011, 02, 16] => 300 
      [2011, 06, 11] => 120 
      [2011, 02, 04] => 120 
      [2010, 12, 19] => 55 
      [2011, 01, 22] => 456 

     ) 

    [108] => Array 
     (
      [2011, 01, 22] => 888 
      [2011, 01, 15] => 123 
     ) 

) 

不幸的是,我用下面的代碼擰起來:

$result = mysql_query("SELECT * FROM data WHERE user_id='$user_id'"); 

$value_array = array(); 
while ($row = mysql_fetch_array($result)) { 
    $value_array[$row['date']] = $row['value']; 
} 

$result = mysql_query("SELECT * FROM data WHERE user_id='$user_id'"); 

$plant_array = array(); 
while ($row = mysql_fetch_array($result)) { 
    $plant_array[$row['plant_id']] = $value_array; 
} 

使我有SA我陣列每個plant_id:

Array 
(
    [109] => Array 
     (
      [2011, 04, 02] => 300 
      [2011, 02, 16] => 300 
      [2011, 06, 11] => 120 
      [2011, 02, 04] => 120 
      [2010, 12, 19] => 55 
      [2011, 01, 22] => 888 // skips value '456' because of repeated date? 
      [2011, 01, 15] => 123 
     ) 

    [108] => Array 
     (
      [2011, 04, 02] => 300 
      [2011, 02, 16] => 300 
      [2011, 06, 11] => 120 
      [2011, 02, 04] => 120 
      [2010, 12, 19] => 55 
      [2011, 01, 22] => 888 // skips value '456' because of repeated date? 
      [2011, 01, 15] => 123 
     ) 

) 

如何創建鍵入到plant_id數組循環,只能從特定plant_id包含數據?

任何幫助,非常感謝!

+0

可能:`$ value_array [] =數組($行[ '日期'],$行[ '值']);` – drudge 2011-02-16 18:08:15

回答

3
$result = mysql_query("SELECT * FROM data WHERE user_id='$user_id'"); 

$output_array = array(); 
while ($row = mysql_fetch_array($result)) { 
    if(!isset($output_array[$row['plant_id']]) || !is_array($output_array[$row['plant_id']])){ 
     $output_array[$row['plant_id']] = array(); 
    } 

    $output_array[$row['plant_id']][$row['date']] = $row['value']; 
} 
+0

主席先生,你是個天才!非常感謝,像魅力一樣工作。 :) – pepe 2011-02-16 18:37:55