搜尋

首頁  >  問答  >  主體

使用foreach循環建立關聯數組的方法

<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>
P粉381463780P粉381463780552 天前532

全部回覆(1)我來回復

  • P粉359850827

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

    要在關聯數組中設定所需的數據,請嘗試以下(已註解)

    $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變數未定義。

    回覆
    0
  • 取消回覆