如何将我的查询结果拆分成两个数组?

时间:2016-12-30 作者:Nanou Ponette

我做了一个查询,得到了8个结果。我需要在2列中显示这些内容,共4项。

这是我的问题:

         $args = array(
                  \'post_type\' => \'event\',
                  \'meta_key\' => \'date\',
                  \'orderby\' => \'meta_value_num\',
                  \'order\' => \'ASC\',
                  \'posts_per_page\' => 8,
                  \'meta_query\' => array(
                      \'key\'       => \'date\',
                      \'value\'     => date(\'Y-m-d\',strtotime("today")),
                      \'compare\'   => \'>=\',
                      \'type\'      => \'DATE\'
                   ),
                );

        $events = new WP_Query( $args );
我尝试使用array\\u splice。示例:

        $firstCol = array_slice($events, 0, 4, true);
        $secondCol = array_slice($events, 4, true);
但这似乎不起作用。如何从结果中获得2个数组?

2 个回复
最合适的回答,由SO网友:Tunji 整理而成

无需拆分数组,只要数完数组的四个元素,就可以关闭第一个div。

$args = array(
    \'post_type\' => \'event\',
    \'meta_key\' => \'date\',
    \'orderby\' => \'meta_value_num\',
    \'order\' => \'ASC\',
    \'posts_per_page\' => 8,
    \'meta_query\' => array(
        \'key\'       => \'date\',
        \'value\'     => date(\'Y-m-d\',strtotime("today")),
        \'compare\'   => \'>=\',
        \'type\'      => \'DATE\'
    ),
);

$events = new WP_Query( $args ); 
$count  = 1;

if ( $events->have_posts() ) : ?>
    <div class="column-1">
    <?php while ( $events->have_posts() ) : $events->the_post();
        // YOUR CONTENT
if ( $count == 4 ) { ?>
    </div>
    <div class="column-2">
<?php }

        $count++;
    endwhile;
    wp_reset_postdata();
endif;
?>
</div>

SO网友:Anas Bouayour

如果我真的理解你的问题,请将数组放入循环并使用变量作为计数器

$count=0; 
$firstCol=array(); 
$secondCol=array(); 
foreach($events as $event) {
   $count++;
   if($count <= 4 ) {
     array_push($firstCol, $event);
   }
   else {
     array_push($secondCol, $event);
   }
}