如何将php数组中的不同变量一起添加

时间:2011-05-26 00:40:14

标签: php mysql sql

我有一个看起来像这样的mysql表:

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

我需要能够从mysql获取此数组并将两个2006值相加。我该怎么做?

4 个答案:

答案 0 :(得分:3)

您是否特别希望PHP能够做到这一点? MySQL可以做数学:
    SELECT year, SUM(value) as value FROM table GROUP BY year

如果你真的想在php(这个脚本是所有年份)中这样做:

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

(强制性引用:谨防上述代码中的错误;我只是证明它是正确的,没有尝试过。 - Donald Knuth)

答案 1 :(得分:2)

选择年份,SUM(值)作为_your_table group by year的值

答案 2 :(得分:2)

$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 />";
}

答案 3 :(得分:0)

针对您的具体案例:

$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