PHP中的多维数组

时间:2016-06-12 09:07:17

标签: php

我有一个名为$ time的变量数组。而我想要做的是计算用户在某个部门停留的秒数,例如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'
          )
    )
);

我有下表:enter image description here

23:26到25:51有145秒的差异。

25:51到27:45有114秒的差异。

28:01到30:46有165秒的差异。

因此,如果我们添加145+ 114 + 166。用户在该部门中停留的总秒数为424秒。

在第9部分: 27:45到28:01有16秒的差异。

我想实现输出:

 $results = array(
           '8' => '424',
           '9' => '16'
 );
它让我发疯了。有人可以帮助我如何实现它或实现它的最佳方式。我试过了:

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

但问题是我无法继续,因为我不知道如何继续下去。谢谢。

2 个答案:

答案 0 :(得分:0)

这应该可以解决问题

function arr2timespent($arr){
  $ret=array();
  for($i=0;$i<count($arr)-1;$i++){
    $startTime=strtotime($arr[$i]["time"]);
    $endTime=strtotime($arr[$i+1]["time"]);
    $diff=$endTime-$startTime;
    $ret[$arr[$i]["dept"]]+=$diff;
  }
  return $ret;
}

迭代数组中的所有条目(除了最后一个)。然后它接受时间差并将其添加到 dept-th 数组条目。
此函数应调用为arr2timespent($time["91"]["100"]);

答案 1 :(得分:0)

问题是你的数组是深层嵌套的,所以你需要一些public function ajax_add() { $response = array( 'success' => false ) ; $this->load->library('form_validation'); // add your validation $this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required'); if ($this->form_validation->run() == FALSE) { $data = array( 'PROVINCE' => $this->input->post('PROVINCE') ); $insert = $this->Provinces_Model->save($data); if($insert){ $response['success'] = TRUE ; $response['message'] = 'Record created successfully' ; } else{ $response['message'] = 'Unable to create record' ; } } else { $response['message'] = 'Invalid data' ; } echo json_encode($response); 循环来获取细节:

.run(function ($rootScope, $location, $state, $mdToast, PhoneFactory) {

        PhoneFactory.get_token().success(function (data) {
            Twilio.Device.setup(data.token, { debug: true, region: "ie1" });
        });
        Twilio.Device.ready(function (device) {
         //do stuff
        });
})

foreach是:

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']);
        }
    }
}

eval.in上看到它。

相关问题