2014-04-15 2 views
0

루프를 반복하고 각 배열 사이의 날짜를 비교하는 두 개의 배열이 있습니다.배열을 반복하고 타임 스탬프를 비교합니다

$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과 비교하면 새 이미지를 다운로드하십시오.

예에서 두 번째 및 네 번째 이미지를 다운로드하고 다른 이미지는 무시합니다.

답변

1

: 대한

+0

+1 나는이 솔루션을 좋아합니다. 그것은 배열 key'd의 내 가정을 동일하게 해결합니다. – tchow002

+0

대단히 감사합니다. – Tim

+0

지연에 대해 유감스럽게 생각합니다. 귀하의 위의 솔루션에 대한 평가판을 실행했습니다. 이 멋진 솔루션을 가져 주셔서 대단히 감사합니다. – Tim

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 
    } 
} 

참고 : 이전 ArrayArray와 newArray의 키가 동일하다고 가정합니다. 즉 id 1이 newArray의 0 지점에 있으면 id 1이 oldArray의 0 지점에 있다고 가정합니다. 나는 이런 식으로 할 것

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 :) 
    } 
} 
0

왜 사용 foreach는, 당신은 간단하게 사용할 수 있습니다. 두 배열의 인덱스에 대해 어떤 가정도하지 않으며 $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 
    } 
} 
관련 문제