Home  >  Q&A  >  body text

How to create associative array using foreach loop

<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>I'm trying to create an associative array using a foreach loop, but I'm getting an error. Any help would be greatly appreciated. </p>
P粉381463780P粉381463780401 days ago408

reply all(1)I'll reply

  • P粉359850827

    P粉3598508272023-08-17 00:34:02

    To set the required data in an associative array, try the following (commented) :

    $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;
    

    Note: $partThe variable is undefined.

    reply
    0
  • Cancelreply