我试图在 foreach 循环中创建一个包含数据的关联数组,但它会引发错误。
这是我的代码:
$featured_posts = get_field('parts', $postId->ID);
if( $featured_posts ):
foreach( $featured_posts as $post ):
setup_postdata($post);
$permalink = get_permalink( $part->ID );
$title = get_the_title( $part->ID );
//make array
$part_pages = array(
$permalink => $title,
);
endforeach;
wp_reset_postdata();
endif;
我做错了什么?如有任何帮助,我们将不胜感激。
要在关联数组中设置所需的数据,请尝试以下(已注释):
$featured_posts = get_field('parts', $postId->ID);
if( $featured_posts ):
// Always initializing your array variable before the foreach loop
$part_pages = array();
foreach( $featured_posts as $post ):
setup_postdata($post);
$permalink = get_permalink( $post->ID );
$title = get_the_title( $post->ID );
// set the permalink as key and the title as value in the array
$part_pages[$permalink] = $title;
endforeach;
wp_reset_postdata();
// Test output
echo '<pre>' . print_r($part_pages, true) . '</pre>';
endif;
注意:
$part
变量未定义。