如何使用 foreach 循环创建关联数组?

问题描述 投票:0回答:1
$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;

我试图用 foreach 循环创建一个关联数组,但它抛出一个错误。如有任何帮助,我们将不胜感激。

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

要将数据设置在关联数组中,请尝试以下操作(已注释):

$featured_posts = get_field('parts', $postId->ID);

if( $featured_posts ):
    $part_pages = array(); // Initializing variable

    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();
    
endif;

// Test output
echo '<pre>' . print_r($part_pages, true) . '</pre>';

注意:

$part
变量未定义。

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