如何创建多维数组?

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. So I thought of using a multidimensional array but not a php here

$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

drzablspw01655860
drzablspw01655860 在这一行$dateOrdered[]=usp_get_meta(false,'usp-custom-80');我们将发布日期添加到数组中,然后我们在函数custom_sort_dt中进行排序,所以我想如果我们也可以添加$id,那么当我们为日期订购数组时也会订购ID
接近 2 年之前 回复
dtu1747
dtu1747 您希望ID在哪里适合您引用值的方式?
接近 2 年之前 回复

2个回答

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);
立即提问
相关内容推荐