简体   繁体   中英

PHP filter and sum array values

I've got a php script with following array (date,task,actor,hh:mm).

Array
(
    [0] => 2013-01-29|Making movies|Laurel|07:30
    [1] => 2013-01-29|Making movies|Hardy|00:30
    [2] => 2013-01-29|Learning PHP|Hardy|07:00
    [3] => 2013-01-29|Singing autographs|Keaton|07:30
    [4] => 2013-01-29|Making movies|Lloyd|07:30
    [5] => 2013-01-28|Learning PHP|Laurel|07:30
    [6] => 2013-01-28|Making movies|Hardy|07:30
    [7] => 2013-01-28|Learning PHP|Keaton|07:30
    [8] => 2013-01-28|Making movies|Lloyd|07:30
    [9] => 2013-01-27|Learning PHP|Laurel|05:30
    [10] => 2013-01-27|Making movies|Laurel|02:30
    [11] => 2013-01-27|Learning PHP|Hardy|07:30
    [12] => 2013-01-27|Making movies|Keaton|07:30
    [13] => 2013-01-27|Making movies|Lloyd|07:30
)

I'd like to create a filter that lists the tasks and sums the time values of each task, for example:

Learning PHP (<-selected option)

2013-01-29 Hardy  07:00
2013-01-28 Laurel 07:30
2013-01-28 Keaton 07:30
2013-01-27 Laurel 05:30
2013-01-27 Hardy  07:30
=======================
TOTAL             35:00

What would be the way to make this happen? Any suggestions or next steps are more than welcome.

This would be easier to filter if you had a multidimensional array. Something like this would work for the current structure though:

$task = "Learning PHP";

foreach($arr as $k=>$v) {
    $pieces = explode("|", $v);
    if($pieces[1]==$task) {
        $total += (int) str_replace(':','',$pieces[3]);
        echo $pieces[0] . " " . $pieces[2] . " " . $pieces[3];
    }
}

echo "Total: " . $total;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM