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 用三极管设计一个单管共射放大电路
  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架