Reputation: 1803
I have the following array which I populated from MySQL:
print_r ($table);
[0] => Array (
[0] => 67122
[idweather] => 67122
[1] => 2014-09-19 00:04:54
[date] => 2014-09-19 00:04:54
[2] => 1
[rainfall] => 1
[3] => 10
[windspeed] => 10
[4] => 13.85
[dewpoint] => 13.85
[5] => 1009.43
[pressure] => 1009.43
[6] => 22.8
[bmp085_temp] => 22.8
[7] => 22.8
[dht22_temp] => 22.8
[8] => 11.58
[abs_hum] => 11.58
[9] => 45.12
[gust] => 45.12
[10] => 0.18
[uvi] => 0.18
[11] => 97.42
[light] => 97.42
[12] => 57.1
[rel_humidity] => 57.1
[13] =>
[wind_dir] =>
)
This is just [0] - the array contains multiple entries for the day. I would like run multiple sorts so I can get the max rainfall, windspeed, bmp085_temp etc for the day
How do I use the sort like this:
sort($table['wind_dir'];
Not sure if this syntax is right as I get:
PHP Warning: sort() expects parameter 1 to be array, null given in test.php on line 167
If it helps this is the mysql code:
$sql_array = "select * from weather where date(date) = curdate();";
if(!$result = $db->query($sql_array)){
die('error running query');
}
$table = array();
while ($row = $result->fetch_array()) {
$table[] = $row;
}
Update:
Ive tried this example:
usort($table, function($a, $b) {
return $a['dht22_temp'] - $b['dht22_temp'];
});
While it appears to be sorting something its not sorted correctly.
echo $table[0]['dht22_temp'];
Prints out a value but its neither the highest or the lowest :(
Update 2:
Got it working with this:
function compare($a, $b)
{
return strnatcmp($a['pressure'], $b['pressure']);
}
usort($table, 'compare');
Upvotes: 1
Views: 76
Reputation: 41873
I suggest use fetch_assoc() in this case. So that in here:
$data = array();
while($row = $result->fetch_assoc()) {
$data['windspeed'][] = $row['windspeed'];
$data['rainfall'][] = $row['rainfall'];
}
rsort($data['rainfall']); // reverse descending
$max_rainfall = reset($data['rainfall']); // get the first
Or:
$max_rainfall = max($data['rainfall']);
Upvotes: 1