如何使用php创建一个循环HTML内容的逻辑

时间:2017-04-28 07:39:48

标签: php html

我有以下HTML代码,它的目的是展示6个广告。 我想要做的是创建一个逻辑循环使用PHP循环以下内容。 例如:目前,Ads1& 2位于顶部的第一个和第二个位置,但是当某个方法获得时 叫做Ads1& 2将进入Ads5和6,而Ads3& 4将进入第一和第二位置(骑车)。 我的解释可能令人困惑,但我想做的是每当调用一个方法(如左轮手枪)时循环两个标签。 实际上我想用下面的代码每2周循环一次内容。我应该使用会话来保存数据吗?我该如何设法做到这一点?我很乐意听取您的意见。

$weekInYearNumber = (int)date('W');
$weekDayNumber = (int)date('w'); 
if ($weekInYearNumber % 2 == 0) {

}

<div class="ContentsWrap">
                <ul class="List_1">
                    <li>
                        <a>Ads1</a>
                    </li>
                    <li>
                        <a>Ads2</a>
                    </li>
                </ul>
                <ul class="List_2">
                    <li>
                        <a>Ads3</a>
                    </li>
                    <li>
                        <a>Ads4</a>
                    </li>
                    <li>
                        <a>Ads5</a>
                    </li>
                    <li>
                        <a>Ads6</a>
                    </li>
                </ul>
</div>

1 个答案:

答案 0 :(得分:0)

您的方法不会按原样运作:

$weekInYearNumber = (int)date('W');
$weekDayNumber = (int)date('w'); 
if ($weekInYearNumber % 2 == 0) {
   // Rotate here
}

首先,如果您每隔一周只进行一次旋转,则必须保存状态,以便保存两周。
其次,每次访问页面时都会运行此代码。这意味着,您还必须保存信息I have already rotated this week 当然,你可以做到这一点,但你也可以不用保存(到数据库)来做到这一点 为此,请使用下面的代码而不是您的代码。评论中的解释:

// Fetch your ads and put them into an array (this is not yet rotated):
$ads = ['ad1', 'ad2', 'ad3', 'ad4', 'ad5', 'ad6'];

// We calculate the number of weeks since 1970-01-01 
// to always have the same basis for our calculation. 
// If you use (int)date('W') you will have a change each new year.
$weeknumber = floor(time() / 86400 / 7);

// Every two weeks, we rotate 2 items, which makes (count of ads) weeks for a full rotation.
$rotate = $weeknumber % count($ads);

//But we only rotate every two weeks
$rotate = floor($rotate / 2);

//Now, we rotate!
for ($i = 0; $i < $rotate; $i++) {
    // Push two elements to the end of the array
    array_push($ads, array_shift($ads));
    array_push($ads, array_shift($ads));
}

// Output your ads as you like and you are done.