使用foreach循环创建关联数组的方法
P粉381463780
2023-08-16 13:21:43
[PHP讨论组]
<p><br /></p>
<pre class="brush:php;toolbar:false;">$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;</pre>
<p>我试图使用foreach循环创建一个关联数组,但是出现了错误。任何帮助将不胜感激。</p>
要在关联数组中设置所需的数据,请尝试以下(已注释):
$featured_posts = get_field('parts', $postId->ID); if( $featured_posts ): // 在foreach循环之前始终初始化数组变量 $part_pages = array(); foreach( $featured_posts as $post ): setup_postdata($post); $permalink = get_permalink( $post->ID ); $title = get_the_title( $post->ID ); // 将链接设置为键,标题设置为值 $part_pages[$permalink] = $title; endforeach; wp_reset_postdata(); // 测试输出 echo '<pre>' . print_r($part_pages, true) . '</pre>'; endif;注意:
$part变量未定义。