dplm47571 2014-04-15 00:18
浏览 257
已采纳

循环遍历数组并比较时间戳

I have two arrays that I like to loop through and compare the dates between each array.

$newArray = Array (
    [0] => Array (
            [id] => 1
            [date] => 26-11-2013 9:30:56 PM
        )
    [1] => Array (
            [id] => 2
            [date] => 30-11-2013 11:20:12 AM
        )
    [2] => Array (
            [id] => 3
            [date] => 26-11-2013 9:30:56 PM
        )
    [3] => Array (
            [id] => 4
            [date] => 30-11-2013 11:20:12 AM
        )
}

$oldArray = Array (
    [0] => Array (
            [id] => 1
            [date] => 26-11-2013 9:30:56 PM
        )
    [1] => Array (
            [id] => 2
            [date] => 26-11-2013 9:30:56 PM
        )
    [2] => Array (
            [id] => 3
            [date] => 26-11-2013 9:30:56 PM
        )
}

foreach ($newArray as $newPhoto) {
    foreach ($oldArray as $oldPhoto) {
        if (strtotime($newPhoto['date']) != strtotime($oldPhoto['date'])) {
            // download new photo
        }
    }
}

I realize that placing the foreach with a foreach is not going to cut it. What is the best way to loop through each of these arrays and compare the dates?

The $newArray has the latest photos and compares with the $oldArray if the timestamps do not match or there is a new one in the list, download the new images.

In the example, I would be downloading the second and fourth images and ignoring the others.

  • 写回答

3条回答 默认 最新

  • donh61500 2014-04-15 00:33
    关注

    I'd do it like this. It does not make any assumptions about the indices of either array, and will be still be fairly efficient as $oldArray grows in size.

    // index $oldArray by id for speed
    $index = array();
    foreach ($oldArray as $photo) {
        $index[$photo['id']] = $photo['date'];
    }
    
    // iterate through new photos, checking if each one needs downloading
    foreach ($newArray as $photo) {
        if (!isset($index[$photo['id']]) // photo is not in $oldArray
                || strtotime($photo['date']) > strtotime($index[$photo['id']])) { // photo is in $oldArray, but a new version is available
            // download new photo
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作