The 前言
construct only works with arrays.
这意味着您必须 使用数组 像这样: 数组( '1', '2', '3' );
Or functions which return an array like get_categories
.
前言
用于遍历数组中的每个键/值对:
$key = array( '1', '2', '3' );
foreach( $key as $value )
print $value;
如果将上述代码包装在打开和关闭php标签中,并将其放入文件中,它将输出123。
那’是对数组使用foreach的最基本示例。
这里’有几个将foreach与键/值对数组以及返回数组的函数一起使用的几个常用示例。
将以下函数添加到您的子主题函数文件中,以查看每个代码段在前端输出的内容。
范例1: 将数组与foreach循环一起使用
下面的示例打印数组中每个键的值:
add_action( 'loop_start', 'for_each_example_1' );
function for_each_example_1() {
$key = array( 'Number 1', 'Number 2', 'Number 3' );
foreach( $key as $value )
echo $value;
}
范例2: 在foreach中使用数组
A different way to code ( array )
when using 前言
:
add_action( 'genesis_entry_header', 'for_each_example_2' );
function for_each_example_2() {
$key = ( 'note 1, note 2, note 3' );
foreach( ( array ) $key as $value )
echo $value;
}
例子3: 与功能一起使用foreach。
This example uses the get_categories
function which returns an array of categories.
add_action( 'genesis_entry_footer', 'for_each_example_3' );
function for_each_example_3() {
$key = get_categories();
foreach( $key as $value )
echo $value->name;
}
例子4: 使用foreach的变量的常用名称
通常,你’ll find the name of 变数 与foreach一起使用’t be named $key
and $value
but more descriptive like $categories as $category
or $tags as $tag
as seen in the following example:
add_action( 'genesis_after_entry', 'for_each_example_4' );
function for_each_example_4() {
$categories = get_categories();
foreach( $categories as $category )
echo $category->name;
}
示例 与get_tags,get_categories和get_terms一起使用foreach
发表评论
你一定是 登录 to post a comment.