"H. Adam" wrote:
hi !
i m trying to calculate an average array from an 2d data array.
my problem is that my function does not generate an average array but just
one value.
but i do not understand why it does not work.
code:
-----
function calculateAverag eRating($rating _matrix)
{
$average_rating = array();
foreach($rating _matrix as $cus_id => $ratings)
{
$counter = 0;
$sum = 0;
foreach($rating s as $pro_id => $item_rate)
{
$counter++;
$sum += $item_rate;
}
echo $cus_id."->".($sum/$counter)."<br> ";
$average_rating[$cus_id] = ($sum / $counter);
}
echo "<hr>";
echo "<table> <tr>";
foreach($averag e_rating as $key => $value);
{
echo "<td>$key::$val ue</td>";
}
echo "</tr></table>";
return $average_rating ;
}
wanted:
input -> output
1 1 1 1
2 2 2 2
4 4 4 4
but my functions just does:
input -> output
1 1 1
2 2 2
4 4 4 4
function calculateAverag eRating($rating _matrix)
{
$average_rating = array();
foreach($rating _matrix as $cus_id => $ratings){
$average_rating[$cus_id] = (array_sum($rat ings) / count($ratings) );
}
echo "<hr>";
echo "<table> <tr>";
foreach($averag e_rating as $key => $value){
echo "<td>$key::$val ue</td>";
}
echo "</tr></table>";
return $average_rating ;
}
This should work if $rating_matrix looks like this:
"cus_id1"=>arra y(int1, int2,...,intN),
"cus_id2"=>arra y(int1, int2,...,intN),
....,
"cus_idN"=>arra y(int1, int2,...,intN),
If it doesn't look like that, please print_r($your_a rray) and post it.
I believe the reason your function didn't work was because of this line:
foreach($averag e_rating as $key => $value);
Your script was interpreting the ";" as the statement to execute in the
foreach. The foreach therefore did nothing. Then the script executed what you
had intended to be the foreach codeblock (the stuff between "{" and "}") once,
as it wasn't within a loop.
Regards,
Shawn
--
Shawn Wilson
sh***@glassgian t.com http://www.glassgiant.com
I have a spam filter. Please include "PHP" in the
subject line to ensure I'll get your message.