首页 > 解决方案 > 如何推送/创建关联数组?

问题描述

我正在运行一个帖子循环,这些帖子有四个我需要关联的属性:标题、日期、链接、位置:

while (have_posts()) : the_post();
    if( !in_array( $post->ID, $already_displayed_ids )) {
        array_push( $thisPostid, $post->ID );
        $title = get_the_title();
        $location = usp_get_meta(false, 'usp-custom-8');
        $link = get_permalink();
        $contentYear = usp_get_meta(false, 'usp-custom-14');
        if ($contentYear >= 0 && $contentYear <= 2019) {
            array_push($yearsArray, $contentYear);
            if (($wp_query->current_post +1) == ($wp_query->post_count)) {
                $yearsArray = array_unique($yearsArray);
                sort($yearsArray);
            }
        }
        array_push( $already_displayed_ids, $post->ID );
    }
endwhile;

基本上我正在运行一个循环,我检查非重复,$already_displayed_ids我需要关联并推送我在这里推送的任何帖子的标题、位置、日期和链接array_push($yearsArray, $contentYear);

目前我只能推送$contentYear但没有linktitle或者location与推送的帖子相关联,我想创建一个关联数组来推送我需要的每个帖子的所有规格。$contentYear是一个带有日期的自定义字段,所以我正在使用这些值生成导航,它们是日期。但是我需要将它们的标题、位置和链接与每个日期相关联,因为我目前不知道如何将这些规范与我推送的时间相关联。

标签: phpwordpressloops

解决方案


这就是我解决它的方法:

while (have_posts()) : the_post();
    if( !in_array( $post->ID, $already_displayed_ids )) {
        array_push( $thisPostid, $post->ID );
        $contentYear = usp_get_meta(false, 'usp-custom-14');
        if ($contentYear >= 0 && $contentYear <= 2019) {
            array_push($yearsArray, 
                array(
                    'year'=> $contentYear,
                    'link'=> get_permalink(),
                    'location'=> usp_get_meta(false, 'usp-custom-8'),
                    'title'=> get_the_title()
                )
            );
        }
        array_push( $already_displayed_ids, $post->ID );
    }
endwhile;

然后我可以做foreach ($yearsArray as $year) {等等echo $year['title']


推荐阅读