php foreach循环内的替代颜色类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php foreach循环内的替代颜色类相关的知识,希望对你有一定的参考价值。

<?php
/**
 * Snippet to show how to add alternate classes to a div within a foreach loop.
 * Author: Gemma Plank
 * Author URL: https://makedo.net
 */

// Get current page ID.
$page_id = get_the_ID();

// Array of class name modifiers.
// These affect the background colour of each panel.
$colours = array(
	'',
	'service-panel--white',
	'service-panel--red',
);

// Initiate our counter.
// This allows us to stop when we reach the maximum number of colour classes & restart.
$i = 0;

// Create args for loop below.
$services_args = array(
	'post_parent' => $page_id,
	'post_type'   => 'any',
	'numberposts' => -1,
	'post_status' => 'any',
);

// Get child posts based on the above args.
$child_services = get_children( $services_args );

// For each post/page within the array.
foreach ( $child_services as $child_service ) {
	// Store each panel class based on position within our $colours array.
	$panel_class = $colours[ $i ];
	
	// Print opening div with new modifier class name printed.
	echo '<div class="service-panel-link' . esc_attr( $panel_class )  . '">';
	
	// Print post title.
	echo esc_html( $child_service->post_title );
	
	// Print closing div tag.
	echo '</div>';

	// Increment our counter.
	$i++;

	// Reset our counter back to zero when our limit of 2 is reached.
	// This will need to change if we alter the number of classes inside the $colours array.
	// NOTE: its technically 3 as we start from 0 not 1.
	if ( $i > 2 ) {
		$i = 0;
	}
}

?>

以上是关于php foreach循环内的替代颜色类的主要内容,如果未能解决你的问题,请参考以下文章

按钮操作块内的 Foreach 循环抛出“Type() 不能符合视图”

php foreach 循环正在做奇怪的行为来添加值

PDO 查询未在 PHP foreach 循环中返回结果

php效率

如何在foreach循环中显示来自PDO的数据

C#中foreach语句的作用?