0

我在 while 循环中有一个 foreach 循环。就使用 $i 和 $i++ 进行迭代而言,我正在使用标准设置。这是我的代码(缩短):

// 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>';
    }
}

我试图让 $i (在 foreach 循环内)在 foreach 循环运行时增加,但我的 PHP 脚本只是超时。当我将 $i++ 移到 foreach 之外时,它工作正常……但那当然不是我需要的。

编辑我刚刚发布了完整的代码。它使用 Joomla 数据库对象进行连接。

4

1 回答 1

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>';
}
于 2013-04-25T06:43:01.403 回答