我已经为这个foreach循环挣扎了一段时间了。我需要做的是从数据库表中获取和值,进行一些计算,然后使用css将它们显示为条形图。但是我的foreach循环只给我表中的最后一个值。任何帮助将非常感激,这里是我的代码的一个样本:
<?php
$total_query = "select sum(amount_recieved) from reciepts";
$total_result = safe_query($total_query);
$total = mysql_fetch_row($total_result);
$query = "select category_id from customer_categories";
$result = safe_query($query);
while($cat_id = mysql_fetch_assoc($result)){
foreach ($cat_id as $cat) {
$sum_query = "select sum(amount_recieved) from reciepts where category =".$cat."";
$sum_result = safe_query($sum_query);
$sum = mysql_fetch_array($sum_result);
$percentage = ($sum[0]/$total[0]) * 100;
echo "
<li title='".$cat.", NGN ".$sum[0].", ".$percentage."%' class='bar' style='
position:absolute;
bottom:0;
left:1%;
float:left;
width:7%;
height:".$percentage."%;
margin-right:1%;
margin-left:1%;
background:#999;'>
</li>";
}
}
?>
您的问题是,您正在定位每个可能被数据检索的栏在完全相同的地方:
echo "
<li title='" . $cat . ", NGN " . $sum[0] . ", " . $percentage . "%' class='bar' style='
position:absolute;
bottom:0;
left:1%;
float:left;
width:7%;
height:" . $percentage . "%;
margin-right:1%;
margin-left:1%;
background:#999;'>
</li>";
浮动到左边和绝对位置,它们都将被覆盖。不需要对这些li元素进行绝对定位,请尝试删除position:absolute;
。
试试这个;$cat['category_id'];