Calculate percentage of unlimited items
I want to list top sellers items based on the sales history MySQL table:
sales(id,item)
----------------
1,Chocolate
2,Chocolate
3,Flowers
Will output:
Chocolate ::开发者_运维知识库 2 Sales :: 67%
Flowers :: 1 Sales :: 33%
How to do that using php?
Thanks
select
name,
round(count(*)/total_row.total*100)
from
sales,
(select count(*) as total from your_tables) as total_row
group by sales.name;
If you have an array of all the items you could do something like
$ary = array('Chocolate','Chocolate','Flowers');
$total = count($ary);
$count = array_count_values($ary);
foreach($count as $item=>$val) {
echo '<p>'.$item.' - '.$val.' Sales - '.($val/$total*100).'%</p>';
}
Turns out array_count_values is a handy little function.
精彩评论