简体   繁体   English

如何创建多维数组?

[英]How to create a multi dimensional array?

I run a loop for posts, these have a date field but this is a string, so I first order by date using a function, and it works. 我为帖子运行一个循环,这些帖子具有日期字段,但这是一个字符串,因此我首先使用功能按日期排序,并且可以正常工作。 But I am missing the ID and I need to associate both the date with its ID as I will then need to run a loop over these ids and have the posts be ordered by dates. 但是我缺少ID,我需要将日期和ID关联起来,因为然后我需要对这些ID进行循环,并按日期对帖子进行排序。 So I thought of using a multidimensional array but not a php here 所以我想在这里使用多维数组而不是PHP

$queryPosts = new WP_Query(array(
    'posts_per_page' => -1,
    'post__in' => $postIds,
    )
);
if( $queryPosts->have_posts() ):
    $dateOrdered = [];
    while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
        $id = $post->ID;
        $dateOrdered[] =  usp_get_meta(false, 'usp-custom-80');
    endwhile;
endif;

function custom_sort_dt($a, $b) {
    return strtotime($a) - strtotime($b);
}
usort($dateOrdered, "custom_sort_dt");
print_r($dateOrdered);

I am expecting an arrays of IDs 我期待一个ID数组

This is how I created the array and resolved 这就是我创建数组并解决的方法

if( $queryPosts->have_posts() ):
    $dateOrdered = [];
    while ( $queryPosts->have_posts() ) : $queryPosts->the_post();
        $id = $post->ID;
        $date = usp_get_meta(false, 'usp-custom-80');
        array_push($postOrdered, $id);
        $dateOrdered[] = array("date"=>$date, "id"=>$id);
    endwhile;
endif;

Please check below code I think it help for you. 请检查以下代码,我认为这对您有帮助。

$array = array(); while ( have_posts() ) {
            the_post();
            get_template_part( 'template-parts/content/content' );
            $id = $post->ID;
            $data = strtotime(get_the_date( 'Y-m-d' ));
            $array[$data][] = array(
                'date' => get_the_date( 'Y-m-d' ),
                'id' => $id
            );
        }
        ksort($array);
        print_r($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM