=============================================== ===================================
解决方案代码:
$array = array();
$i = 1;
while( $i <= $instance['posts_num'] ) {
$array['tab'.$i.'_title'] = 'Category Heading';
$array['tab'.$i.'_thumb'] = 'Insert link here';
$array['tab'.$i.'_featured'] = 'Insert link here';
$array['tab'.$i.'_description'] = 'Insert category desciption';
$array['tab'.$i.'_link'] = 'Insert category link';
$i += 1;
}
$instance = wp_parse_args( (array)$instance, array(
'heading' => 'Featured Area',
'title' => '',
'posts_num' => 1,
(array) $array
) );
=============================================== ===================================
如何使用while循环创建数组。
我试图在简单的wordpress插件中使用while循环创建一个数组。我的代码如下:
$instance = wp_parse_args( (array)$instance, array(
'heading' => 'Featured Area',
'title' => '',
'posts_num' => 1,
$array = array();
$i = 1;
while( $i <= $instance['posts_num'] ) {
$array[] = 'tab'.$i.'_title' => 'Category Heading',
$array[] = 'tab'.$i.'_thumb' => 'Insert link here',
$array[] = 'tab'.$i.'_featured' => 'Insert link here',
$array[] = 'tab'.$i.'_description' => 'Insert category desciption',
$array[] = 'tab'.$i.'_link' => 'Insert category link',
$i += 1;
}
) );
我只是想确认一下我是否做得正确。
我想生成这样的数组:
'tab1_title' => 'Category Heading',
'tab1_thumb' => 'Insert link here',
'tab1_featured' => 'Insert link here',
'tab1_description' => 'Insert category desciption',
'tab1_link' => 'Insert category link',
'tab2_title' => 'Category Heading',
'tab2_thumb' => 'Insert link here',
'tab2_featured' => 'Insert link here',
'tab2_description' => 'Insert category desciption',
'tab2_link' => 'Insert category link',
答案 0 :(得分:2)
您正试图在array()
内放置一个while循环。这不会起作用。在调用wp_parse_args
之前构造数组,然后将完成的数组传递给。{/ p>
答案 1 :(得分:1)
while( $i <= $instance['posts_num'] ) {
$array["tab{$i}_title"] = 'Category Heading';
//...Repeat for others here.
$i += 1;
}
array(4) {
["tab0_title"]=>
string(16) "Category Heading"
["tab1_title"]=>
string(16) "Category Heading"
["tab2_title"]=>
string(16) "Category Heading"
["tab3_title"]=>
string(16) "Category Heading"
}
答案 2 :(得分:0)
您的代码的问题在于您使用了错误的语法/逻辑。
示例:
$array['tab'.$i.'_title'] = 'Category Heading';
$array['tab'.$i.'_thumb'] = 'Insert link here';
$array['tab'.$i.'_featured'] = 'Insert link here';
$array['tab'.$i.'_description'] = 'Insert category desciption';
$array['tab'.$i.'_link'] = 'Insert category link';