簡體   English   中英

在CodeIgniter中從數組中添加數據庫值

[英]add database value off array in CodeIgniter

我想添加從數據庫獲得的值。

我有一個輸出

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。

如何添加?

循環遍歷數組,並將每個objectTOTAL_TIME屬性的值TOTAL_TIME在一起。

$sum = 0;
foreach ($array as $object){
    $sum += $object->TOTAL_TIME;
}

print $sum;

您也可以使用array_walk作為循環的替代方法

$sum = 0;
array_walk($array,function($object) use (&$sum){
    $sum += $object->TOTAL_TIME;
});

print $sum;

您可以使用array_reduce

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

array_reduce @ php.net

如果您想以總值TOTAL_TIME的可變總和存儲,請嘗試此操作

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

如果您從數據庫中獲得該數據,我建議在查詢中使用SUM,這樣我們就可以返回變量,而無需執行foreach循環。

$array =  (array) $yourObject;

然后應用array_sum

使用此代碼

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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM