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
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); 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.