php逻辑数组和旧的vs新变量

时间:2013-11-28 14:33:37

标签: php mysql arrays logic

这是我的问题,感觉很简单,但我错过了一些东西。

我有一个数组(mysql表中的行):

id 125
    [0] => 2
    [1] => 3000.000

id 122
    [0] => 3
    [1] => 3000.000

id 125
    [0] => 5
    [1] => 3000.000

id 122
    [0] => 1
    [1] => 3000.000

每个唯一身份证我需要总计array[0]

id[122] = 4;
id[125] = 7;

到目前为止,我有:

while($get_movementsr=mysql_fetch_array($get_movements)){

    $qty = $get_movementsr['qty'];
    $newid = $get_movementsr['id'];

//here i want to load an array
//if the next id in the loop is the same i want it to add else if its not the same
//a new array id musty be created and total, basically check for new variable vs old //variable - im a noob sorry guys 

 $total[$newid] += $qty;

    $old = $newid;
}

2 个答案:

答案 0 :(得分:0)

如果你在循环之外定义$total,你会得到你想要的......

$total = array();

while($get_movementsr=mysql_fetch_array($get_movements)){
    $qty = $get_movementsr['qty'];
    $newid = $get_movementsr['id'];

    $total[$newid] += $qty;
}

答案 1 :(得分:0)

//(PHP 5 >= 5.5.0)
function total($result, $field)
{
    return count(array_column($result, $field));
}