【问题标题】:PHP foreach loop only outputting the last value from mysql tablePHP foreach 循环仅输出 mysql 表中的最后一个值
【发布时间】:2016-07-05 09:24:05
【问题描述】:

我已经为这个 foreach loopp 苦苦挣扎了一段时间了。我需要做的是从我的数据库表中获取总和值,进行一些计算,然后使用 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>";

            }
    }

?>

【问题讨论】:

  • while 循环遍历行,foreach 循环遍历列,这是您想要发生的吗?
  • customer_categories 表中有多少个类别?
  • 真的不应该再发这个了:stackoverflow.com/questions/12859942/…

标签: php foreach


【解决方案1】:

您的问题是您将数据可能检索到的每个条定位在完全相同的位置:

        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;

【讨论】:

  • @Immanuel 我很高兴听到,请您点击我的回答投票吗?谢谢! :)
【解决方案2】:

试试这个; $sum_query = "select sum(amount_recieved) from reciepts where category=".$cat['category_id'];

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多