English 中文(简体)
PHP 每五个项目
原标题:PHP foreach loop every fifth item
  • 时间:2012-04-23 22:52:00
  •  标签:
  • php

我有一个简单的旁观:

foreach ( $posts as $index => $posts )

以及反之:

if( $index % 5 + 1 == 5 ) {
//do something 
}

我每页有15个员额,除了最后一点点,它应当做些什么,但我如何做?

So it becomes:

POST
POST
POST
POST
POST
DO SOMETHING
POST
POST
POST
POST
POST
DO SOMETHING
POST
POST
POST
POST
POST
最佳回答

If you know, you have 15 posts, and need every 5th but not the last... That means you need to make something with the 5th and 10th one, am i right? So why not check that?

if($index == 4 || $index == 9)
问题回答
if( $index % 5 + 1 == 5 && $index != 14) {
//do something 
}

改变你的条件,使指数不等于你阵列的最后指数。 这14或15条(取决于你何时从0或1开始)。

检查范围操作员,对这种情况非常有用。

http://php.net/manual/en/function.range.php

foreach (range(0, $index, 5) as $number) {
    // do something with $posts[$number]
}

红十字与红新月联会不需要联系阵列:

$posts=array(a,b,a,b,a,b,a,b,a,b,a,b,a,b,a);

for($i=0;$i<count($posts);$i++)
{
if($i % 5 + 1 == 5 && $i != count($posts) - 1)
{
echo $i." as ".$posts[$i];
}
}

这将消除最后的每一个员额,只重复第五个员额。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签