如何在PHP中访问我的foreach循环之外的变量?

时间:2013-04-25 06:33:55

标签: php

我在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>';
    }
}

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

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

1 个答案:

答案 0 :(得分: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>';
}