开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜