如何在foreach循环中使用数据创建关联数组? [已关闭]

问题描述 投票:0回答:1

我试图在 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;

我做错了什么?如有任何帮助,我们将不胜感激。

php wordpress loops foreach associative-array
1个回答
1
投票

要在关联数组中设置所需的数据,请尝试以下(已注释)

$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
变量未定义。

© www.soinside.com 2019 - 2024. All rights reserved.