2013-04-25 6 views
0

while 루프 내부에 foreach 루프가 있습니다. 나는 표준 설정을 사용하여 $ i와 $ i ++를 반복한다. 단지 시간이 초과 내가 때 foreach 루프가 실행을 증가하기 전합니다 (foreach 루프 내부에) $를 얻으려고PHP에서 foreach 루프 외부에있는 변수에 어떻게 액세스합니까?

// Get a database object 
$db = JFactory::getDBO(); 
date_default_timezone_set("America/Chicago"); 
$month = date('n'); 
$day = date('j'); 
$year = date('Y'); 

$currentDay = $month.'/'.$day.'/'.$year; 
//echo $currentDay; 

// create the list of accessories 
$i = 0; 
while($i < 20) { 

    $yesterday = strtotime ("-$i days" , strtotime ($currentDay)) ; 
    $yesterday = date ('n/j/Y' , $yesterday); 

    $query = "SELECT * FROM #__cappz_homelinks WHERE date='{$yesterday}' ORDER BY id ASC"; 
    // Executes the current SQL query string. 
    $db->setQuery($query); 
    // returns the array of database objects 
    $list = $db->loadObjectList(); 

    if($list[0]->date) {//if there's a date 
     echo '<h2>'; 
     echo $yesterday; 
     echo '</h2>'; 

     echo '<ul>'; 
     foreach ($list as $item) { 
      echo '<li>'; 
      echo '<a target="_blank" href="'.$item->url.'">'.$item->headline.$i.'</a>'; 
      echo '</li>'; 
      $i++; 
     } 
     echo '</ul>'; 
    } 
} 

,하지만 내 PHP 스크립트를이 (단축) 내 코드입니다. foreach 밖에서 $ i ++를 움직이면 제대로 동작하지만 ... 물론 내가 필요한 것은 아닙니다.

수정 방금 ​​전체 코드를 게시했습니다. 그것은 Joomla 데이터베이스 개체를 사용하여 연결하고 있습니다.

+3

'$ list'에는 최소한 20 개의 요소가 있습니까? – Dogbert

+1

list [0]에 날짜가있는 항목이 충분하지 않은 경우 foreach 루프에서 $ i는 결코 20에 도달하지 않으며 테스트가 아닌 경우에는 증가하지 않습니다. 따라서 영구 루프가됩니다 (귀하의 데이터베이스 코드 않습니다) –

+0

그래. foreach 외부에서 $ i ++를 움직일 때 while 루프 내부에서 여전히 잘 작동합니다. – Micah

답변

3

이것은 루프 또는 카운터 대신 SQL LIMIT를 사용하여 목록을 단 20 개의 항목으로 제한하는 방법입니다.

// Get a database object 
$db = JFactory::getDBO(); 
date_default_timezone_set("America/Chicago"); 
$month = date('n'); 
$day = date('j'); 
$year = date('Y'); 

$currentDay = $month.'/'.$day.'/'.$year; 
//echo $currentDay; 

// create the list of accessories 

$yesterday = strtotime ("-$i days" , strtotime ($currentDay)) ; 
$yesterday = date ('n/j/Y' , $yesterday); 

$query = "SELECT * FROM #__cappz_homelinks WHERE date='{$yesterday}' ORDER BY id ASC LIMIT 20"; 
// Executes the current SQL query string. 
$db->setQuery($query); 
// returns the array of database objects 
$list = $db->loadObjectList(); 

if(count($list)>0 && $list[0]->date/*not sure if this is needed*/) {//if there's a date 
     echo '<h2>'; 
     echo $yesterday; 
     echo '</h2>'; 

     echo '<ul>'; 
     foreach ($list as $item) { 
      echo '<li>'; 
      echo '<a target="_blank" href="'.$item->url.'">'.$item->headline.$i.'</a>'; 
      echo '</li>'; 
     } 
     echo '</ul>'; 
} 
+0

감사 ... 작동했습니다! 왜 이것이 잘못된 코드 디자인인지 말해 줄 수 있습니까? 나는 위로 전체 코드를 다시 게시했습니다 ... – Micah

+0

@Micah 20 개 항목을 검색하기 위해 20 번까지 데이터베이스 연결을 다시여 셨습니다. 아마도 incretement에 $ i 변수를 사용하고 다른 데이터 집합을 선택했을 가능성이 있다고 생각했지만 실수였습니다. PHP 카운터 대신 SQL LIMIT을 사용하도록 코드를 수정했습니다. 마찬가지로 쉽게 "$ i ++; if ($ i> 20) exit"를 추가 할 수 있습니다. foreach 루프 내부의 맨 아래에 동일한 결과가 나타납니다. – Brent

관련 문제