PHP:如何从list()中获得总和?

It's taking me quite some time to solve this problem and decided to ask for help.

I have a php code here to calculate total hours and minutes. I know I should have used php SUM(totalhours) but I want to try it different way.

$query_hours gets column 'totalhours'

foreach($query_hours->result() as $row){
    $tt = $row->totalhours;     // 10:58 | 09:20 | 10:00
    list($tt1,$tt2) = explode(':', $tt);  //$tt1 = 10 | 09 | 10
}

the thing now is how can I get the sum of $tt1 which is 29? I tried array_sum($tt1) but I got an error, something like invalid argument, string given. Already did an initialization $thours = array($tt1) before using array_sum() but still got another error :3

Since you said you want to do it the way you are and don't want to use Mysql SUM(), you can use a variable to hold the sum over the loop

$sum=0;
foreach($query_hours->result() as $row){
   $tt = $row->totalhours;     // 10:58 | 09:20 | 10:00
   list($tt1,$tt2) = explode(':', $tt);  //$tt1 = 10 | 09 | 10
   $sum+=$tt1;
 }
echo $sum;

Use like below

$total=0;
foreach($query_hours->result() as $row){
   $tt = $row->totalhours;     // 10:58 | 09:20 | 10:00
   list($tt1,$tt2) = explode(':', $tt);  //$tt1 = 10 | 09 | 10
   $total+=$tt1;
 }
echo $total; //your result here

I think this may solve your problem, try this:

$sum=0;
foreach($query_hours->result() as $row){
   $tt = $row->totalhours;     // 10:58 | 09:20 | 10:00
   list($tt1,$tt2) = explode(':', $tt);  //$tt1 = 10 | 09 | 10
   $sum+=$tt1;
 }
echo $sum;

What is the error you get when using array_sum ? as long as you give it an array there shouldn't be any errors.

$sum = 0;
foreach($query_hours->result() as $row){
    $tt = $row->totalhours;     // 10:58 | 09:20 | 10:00
    $sum += array_sum(explode(':', $tt));  //$tt1 = 10 | 09 | 10
}