我有一个PHP项目(WordPress帖子)数组,我循环遍历它来创建一个3x3的帖子网格。
使用jQuery,我将一个CSS类应用于中间列项目,如下所示:
$('#grid li:nth-child(3n+2)').addClass('middle');
我如何在PHP中实现这一点?我可以设置一个与2,5,8,11, etc...匹配的计数器吗
发布于 2012-04-11 01:52:27
你知道PHP中的循环吗?在不了解更多关于您的PHP代码到底要实现什么的情况下,我只能建议这样做:
$posts = array(); //The whatever thing that contains the posts you are concerned about
for ($i = 1; $i<=count($posts); $i++) {
if($i == /*selector condition*/) {
//do what you do with the targeted posts
} else {
//do what you do with all others
}
}(参见http://www.w3schools.com/php/php_looping_for.asp)
小附注:你通常会从$i=0开始计数,但我假设如果你在谈论帖子,他们可能会从1开始计数,而不是从0开始计数。
发布于 2016-01-29 19:11:37
function nthChild($multiplier, $addition, $max)
{
$validInedexes = array();
for ($n = 0; $n < $max; $n++)
{
$idx = $multiplier * $n + $addition;
if ($idx > $max)
{
return $validInedexes;
}
$validInedexes[] = ($idx - 1);
}
}上面的函数将根据输入给出有效的索引。然后在任何循环中按索引匹配。对此使用in_array函数或任何您喜欢的函数。
发布于 2012-04-11 02:00:18
$my_query =新的WP_Query('category_name=special_cat&posts_per_page=10');?>
$query = new WP_Query('...');
$posts = ($count = $query->post_count) ? range(1, $count) : array();
foreach (array_chunk($posts, 3) as $row => $rowIndexes)
{
foreach ($rowIndexes as $column => $index)
{
$query->the_post();
$middle = $column === 1;
...
}
}https://stackoverflow.com/questions/10093754
复制相似问题