PHP - Help setting up loops to build multi-array
I have a database table that contains the following:
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
I need to create an array for user_id 68 that is keyed to plant_id and looks like this:
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
)
)
Unfortunately I am screwing it up with the following code:
$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;
}
which gives me the same arrays for each 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
)
)
How do I create the array loops keyed to plant_id, containing data only from that specific plant_id?
Any help is greatly appreciated!
$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'];
}
精彩评论