Jump to content

[SOLVED] help with averaging.


fou2enve

Recommended Posts

I am writing an auditing script for a friend that runs a motel. He's got all the data in a mysql database. He wants to see what his average room rate he's been giving his customers. I've got this so far:

 

function average($arr)
{
   		if (!is_array($arr)) return false;

   		return array_sum($arr)/count($arr);
}
$array = array($Room101Rate, $Room102Rate, $Room103Rate);
echo average($array); 

 

but I want this to be completely automated, but the problem is that I have all the rooms in the array (i only included three, but there are 40 total, you get the idea)

 

heres the problem, if room 102 and 103 have not been sold I get a result of 0 for those rooms. This on a large scale could affect the average drastically. So how can I calculate the average correctly?

 

Any help is appreciated.

thanks.

Link to comment
https://forums.phpfreaks.com/topic/52487-solved-help-with-averaging/
Share on other sites

not tested... but it should work :-)

function average($arr){
if(!is_array($arr)) return false;
return array_sum($arr)/count($arr);
}
function cleanup($array){
$out=array();
foreach($array as $k=>$v){
  if(!empty($array[$k])) $out[$k]=$v;
}
return $out;
}
$array=cleanup(array('134.32', '', '123.12'));
echo average($array); 

You can add the rates into the array in a loop that retrieves all the rooms with a non-zero rate:

<?php
$q = "select roomrate from YourTable where roomrate > 0";
$rs = mysql_query($q);
$rr = array();
while ($row = mysql_fetch_assoc($rs))
   $rr[] = $row['roomrate'];
echo average($rr);
?>

Or you can let MySQL do all the work:

<?php
$q = "select sum(roomrate) as s_rm, count(roomrate) as c_rm where roomrate > 0";
$rs = mysql_query($q)
$rw = mysql_fetch_assoc($rs);
$echo $rw['s_rm'] / $rw['c_rm'];
?>

Please note that my MySQL syntax maybe slightly off.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.