开发者

How to add distinct variables from a php array together

I have a mysql table that looks like this:

id - year - value
-----------------
1  - 2004 - 10 
2  - 2005 - 15 
3  - 2006 - 8 
4  - 2006 - 14
5  - 2007 - 20
6  - 2008 - 25

I need to be able to fetch this array from mysql and have the the two 2006 values added together. 开发者_运维技巧How do I do this?


Do you specifically want PHP to do it?
MySQL can do the math:
SELECT year, SUM(value) as value FROM table GROUP BY year

If you really want to do it in php (this script is for all years):

$rs = mysql_query("SELECT * FROM table");
while ($row = mysql_fetch_assoc($rs)){
  $value[$row['year']] += $row['value'];
}

(Obligatory quote: Beware of bugs in the above code; I have only proved it correct, not tried it. - Donald Knuth)


$query = "SELECT t.year, 
                 SUM(t.value) AS sumValue
            FROM table t
        GROUP BY t.year";

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result))
{
    echo $row['year']. " = ". $row['sumValue'];
    echo "<br />";
}


select year, SUM(value) as value from _your_table group by year


for your specific case:

$sql = "SELECT year, SUM( value ) AS total FROM table_name WHERE year = 2006";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);

echo $result['total']; // 22
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜