useruseruser useruseruser - 5 months ago 8
PHP Question

Multidimentional array in PHP

I have a variable array named $time. And what I want to do is to count the number of seconds where the user stayed in the certain department for example dept no 8.

$time = array(
'91' => array(
'100' => array(
'0' =>array(
'id' =>'15',
'time' => '2014/05/28 00:23:26',
'dept' => '8'
),
'1' =>array(
'id' =>'15',
'time' => '2014/05/28 00:25:51',
'dept' => '8'
),
'2' =>array(
'id' =>'15',
'time' => '2014/05/28 00:27:45',
'dept' => '9'
),
'3' =>array(
'id' =>'15',
'time' => '2014/05/28 00:28:01',
'dept' => '8'
)
'4' =>array(
'id' =>'15',
'time' => '2014/05/28 00:30:46',
'dept' => '4'
)
)
);


I have the following table:enter image description here

23:26 to 25:51 has a 145 difference of seconds.

25:51 to 27:45 has a 114 difference of seconds.

28:01 to 30:46 has a 165 differenceof seconds.

So if we add them
145+ 114 + 166
. The total seconds that the user stayed in that dept is
424
seconds.

And in dept 9:
27:45 to 28:01 has a 16 difference of seconds.

I want to achieve the output of:

$results = array(
'8' => '424',
'9' => '16'
);


It driving me crazy. Can someone help me how to achive it or what is the best way to implement it. I tried the :

$timeFirst = strtotime('2016/05/26 00:27:45');
$timeSecond = strtotime('2016/05/26 00:28:01');
$differenceInSeconds = $timeSecond - $timeFirst;
print_r($differenceInSeconds);


But the problem is I can't proceed because I don't have any idea how to continue it. Thank you.

Answer

The thing is that your arrays are deeply nested, so you need a few foreach loops to get to the details:

foreach($time as $arr) {
    foreach($arr as $visits) {
        foreach($visits as $i => $visit) {
            if ($i == count($visits)-1) break;
            $results[$visit['dept']] += 
                strtotime($visits[$i+1]['time']) - strtotime($visit['time']);
        }
    }
}

$results is:

Array
(
    [8] => 424
    [9] => 16
)

See it run on eval.in.