我有两个数组,我喜欢循环并比较每个数组之间的日期。
$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
}
}
}
我意识到将foreach
与foreach
放在一起并不会削减它。循环遍历每个数组并比较日期的最佳方法是什么?
$newArray
包含最新照片,并与$oldArray
进行比较,如果时间戳不匹配或列表中有新照片,请下载新图片。
在这个例子中,我将下载第二张和第四张图像而忽略其他图像。
答案 0 :(得分:1)
$oldArray
的增长,它仍然会相当有效。
// 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
}
}
答案 1 :(得分:0)
foreach ($newArray as $key => $newPhoto) {
//If the key doesn't exist in $oldArray it is new
if(!isset($oldArray[$key])){
//download new photo
}
elseif (strtotime($newPhoto['date']) != strtotime($oldArray[$key]['date'])) { //timestamp mismatch
//download new photo
}
}
注意:我假设你的oldArray和newArray的键控方式相同。即如果id 1位于newArray的0
点,我假设id 1位于oldArray中的0
点。
答案 2 :(得分:0)
为什么要使用foreach,您只需使用:
for($i=0; $i<sizeof($newArray); $i++){
if(strtotime($newArray[$i]['date']) != strtotime($oldArray[$i]['date'])){
//new photo do sth
}else {
//old photo do sth or not :)
}
}