Output meta into arrays

时间:2016-10-27 作者:markb

我正在创建一个循环,它不会输出任何用户可见的内容,但需要稍后创建一个计算。

我有:

// posts for the week mon-fri
$week_array = array(
    \'posts_per_page\'   => -1,
    \'post_type\'        => \'post\',
    \'post_status\'      => array(\'publish\'),
    \'date_query\'       => array(
        \'before\'    => \'next Saturday\',
        \'after\'     => \'last Monday\',
    )
);

$week_count = get_posts( $week_array );

$array01 = array();
$array02 = array();

echo \'<h1>\' . count( $week_count ) . \' posts this week</h1>\';
foreach( $week_count as $post ) {
    setup_postdata($post);
    $a = rand(5,15);

    $meta_array01 = get_post_meta( $post->ID, \'meta_login\',  true );
    $meta_array02 = get_post_meta( $post->ID, \'meta_logout\', true );


     $array01[$post->ID] = $meta_array01;
     $array02[$post->ID] = $meta_array02;

}
wp_reset_postdata();
我的主要意图是输出如下内容:

array(
    [167] => array(
                \'meta_login\'  => 2016-10-25 18:34:55
                \'meta_logout\' => 2016-10-25 19:15:12
             ),

    [168] => array(
                \'meta_login\'  => ...
                \'meta_logout\' => ...
             )
    ... // and so on for each matching post
);
但我无法理解这一点,所以我想将上面的两个数组合并为一个,但是当我使用array_merge_recursive() 我得到一个从0到最后一个帖子数的数组,但失去了它们的顺序。

实际上,我的目标是计算两个元字段之间的时间。

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

添加\'fields\' => \'ids\' 跳过设置帖子,只需在foreach.

$week_args = array(
    \'posts_per_page\' => - 1,
    \'post_type\'      => \'post\',
    \'post_status\'    => array( \'publish\' ),
    \'fields\'         => \'ids\',
    \'date_query\'     => array(
        \'before\' => \'next Saturday\',
        \'after\'  => \'last Monday\',
    ),
);

$week_array = get_posts( $week_args );
$week_count = count( $week_array );

printf( \'<h1>%s posts this week</h1>\', $week_count );

$dates = array();
foreach ( $week_array as $post_id ) {

    $login  = get_post_meta( $post_id, \'meta_login\', true );
    $logout = get_post_meta( $post_id, \'meta_logout\', true );

    $dates[ $post_id ] = array(
        "meta_login"  => $login ? $login : 0,
        "meta_logout" => $logout ? $logout : 0,
        "dif"         => abs(strtotime($logout) - strtotime($login)),
    );
}

echo "<pre>";
print_r( $dates );

SO网友:Alex Protopopescu

查看get\\u post\\u meta WP函数https://developer.wordpress.org/reference/functions/get_post_meta/ 显示将其与参数$single设置为(bool)“true”一起使用时,函数将返回请求的meta\\u键的meta\\u值。如果参数$single设置为(bool)“false”,那么它将为请求的meta\\u键返回一个或多个meta\\u值的数组(如果有多个值与查询匹配)。

因此,要获得所需的输出,您可以这样做:

foreach( $week_count as $post ) {
    setup_postdata($post);
    $a = rand(5,15);

     $meta_array[$post->ID] = array( \'meta_login\' => get_post_meta($post->ID, \'meta_login\',  true), 
                                     \'meta_logout\' => get_post_meta($post->ID, \'meta_logout\', true)
                                    );
}