在CodeIgniter中从数组中添加数据库值

时间:2016-05-17 12:09:18

标签: php codeigniter-3

我想添加从数据库中获取的值..

我的输出

Array ( 
[0] => stdClass Object ( [TOTAL_TIME] => 10.58 ) 
[1] => stdClass Object ( [TOTAL_TIME] => 9.23 ) 
[2] => stdClass Object ( [TOTAL_TIME] => 10.35 ) 
[3] => stdClass Object ( [TOTAL_TIME] => 10.10 ) 
[4] => stdClass Object ( [TOTAL_TIME] => 9.95 ) 
[5] => stdClass Object ( [TOTAL_TIME] => 3.40 ) 
[6] => stdClass Object ( [TOTAL_TIME] => 9.90 ) 
[7] => stdClass Object ( [TOTAL_TIME] => 10.63 ) 
[8] => stdClass Object ( [TOTAL_TIME] => 10.48 ) 
[9] => stdClass Object ( [TOTAL_TIME] => 9.43 ) 
[10] => stdClass Object ( [TOTAL_TIME] => 6.42 ) 
[11] => stdClass Object ( [TOTAL_TIME] => 10.12 ) 
[12] => stdClass Object ( [TOTAL_TIME] => 9.33 ) 
[13] => stdClass Object ( [TOTAL_TIME] => 5.53 ) 
[14] => stdClass Object ( [TOTAL_TIME] => 9.35 ) 
[15] => stdClass Object ( [TOTAL_TIME] => 9.60 ) 
[16] => stdClass Object ( [TOTAL_TIME] => 10.08 ) 
[17] => stdClass Object ( [TOTAL_TIME] => 10.03 ) 
[18] => stdClass Object ( [TOTAL_TIME] => 7.73 ) 
[19] => stdClass Object ( [TOTAL_TIME] => 16.82 ) 
[20] => stdClass Object ( [TOTAL_TIME] => 16.55 ) )

我想要做的就是添加这些值。

我已经做过了

$sum = array_sum($data)

但它不起作用。我得到的唯一输出是0。

如何添加?

5 个答案:

答案 0 :(得分:2)

遍历数组并将每个TOTAL_TIME的{​​{1}}属性的值汇总在一起。

object

您也可以使用$sum = 0; foreach ($array as $object){ $sum += $object->TOTAL_TIME; } print $sum; 作为循环的替代

array_walk

答案 1 :(得分:1)

您可以使用array_reduce

$total_time = array_reduce($arr, function($carry, $item) {
    return $carry += $item->TOTAL_TIME;
}, 0);

array_reduce @ php.net

答案 2 :(得分:0)

如果你想以变量值TOTAL_TIME存储,请试试这个

$total_time = 0;
if (!empty($data)) {
    foreach ($data as $value) {
        $total_time += $value->TOTAL_TIME;
    }
}

如果从数据库中获取数据,我建议在查询中使用SUM,这样我们就返回变量,不需要执行foreach循环。

答案 3 :(得分:0)

$array =  (array) $yourObject;

然后你申请array_sum

答案 4 :(得分:0)

使用此代码

function convertObjectToArrayWithSum($data)
{
    if (is_object($data))
    {
        $data = get_object_vars($data);
    }
    if (is_array($data))
    {
        $input = array_map(__FUNCTION__, $data);
        array_walk_recursive($input, function($item, $key) use (&$final) {
            $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
        });
        return $final;
    }
    return $data;
}
print_r(convertObjectToArrayWithSum($data));