将数组和订单集和子集合并为一个

时间:2016-04-05 作者:EliChan

我有两个数组,它们通过两个不同的自定义键对帖子进行过滤和排序。我需要做的是合并数组,并按它们自己的自定义键对它们进行排序,以避免先有数组a的列表,然后是数组b的列表。我尝试了不同的方法,但没有人真正给我带来任何好的结果。我尝试的最后一个是usort,但它基本上没有用(两个合并的数组已经像这样排序了,它只首先得到第二个数组,因为它没有第一个数组的自定义键)。

$series_post = get_posts(array(
    \'numberposts\'   => -1,
    \'post_type\' => \'lyric\',
    \'meta_query\'    => array( array(\'key\' => \'sd_game_series\',\'value\' => \'\',\'compare\' => \'!=\'), array(\'key\' => \'sd_game_type\',\'value\' => \'-Original-\',\'compare\' => \'!=\')),//gets all post with series
    \'orderby\' => array(
        \'sd_game_series\' => \'ASC\',
        \'sd_game\' => \'ASC\',
        \'sd_title\' => \'ASC\')
));

$games_post = get_posts(array(
    \'numberposts\'   => -1,
    \'post_type\' => \'lyric\',
    \'meta_query\'    => array( array(\'key\' => \'sd_game_series\',\'value\' => \'\',\'compare\' => \'=\'), array(\'key\' => \'sd_game_type\',\'value\' => \'-Original-\',\'compare\' => \'!=\')),//gets all post without series
    \'orderby\' => array(
        \'sd_game_series\' => \'ASC\',
        \'sd_game\' => \'ASC\',
        \'sd_title\' => \'ASC\')
));

$merged_arrays = array_merge( $series_post, $games_post );
//NOW I NEED TO USORT THE MERGED ARRAYS
usort( $merged_arrays, function( $a, $b ){
    // sort first by series name
    $compare = strnatcmp(get_post_meta($a->ID, \'sd_game_series\', true), get_post_meta($b->ID, \'sd_game_series\', true));
    // if series names are identical, sort by game name
    if(!$compare) {
        return strnatcmp(get_post_meta($a->ID, \'sd_game\', true), get_post_meta($b->ID, \'sd_game\', true));
    }else{
        return $compare;
    }

});
$posts = $merged_arrays;
第一个数组有一个sd\\u game\\u series值并首先按其排序,第二个数组没有sd\\u game\\u series,只按sd\\u game排序(sd\\u game\\u series是sd\\u game的子集,因此每个带有sd\\u game\\u series的帖子在sd\\u game中也有一个值,但不是每个sd\\u game都有一个sd\\u game\\u series)
我基本上需要按字母顺序对两个数组的结果进行排序
这有可能吗?

1 个回复
SO网友:Behzad

您可以检查get_post_meta 之前args, 示例:

// Get post meta
$game = get_post_meta($post->ID, \'sd_game\', true);
$game_series = get_post_meta($post->ID, \'sd_game_series\', true);

// Check which meta
if( !empty(  $game ) ) {
    $key = \'sd_game\';
} else {
    $key = \'sd_game_series\';
}

$posts = get_posts(array(
    \'numberposts\'   => -1,
    \'post_type\' => \'lyric\',
    \'meta_query\'    => array( 
       array(
          \'key\' => $key,
          \'value\' => \'\',
          \'compare\' => \'!=\'
       ), 
       array(
          \'key\' => \'sd_game_type\',
          \'value\' => \'-Original-\',
          \'compare\' => \'!=\'
       )
);
希望这对您有所帮助;)

相关推荐

how can sort my column

如何添加订单?add_filter(\'manage_articles_posts_columns\', function ( $columns ) { if( is_array( $columns ) && ! isset( $columns[\'post_views\'] ) ) $columns[\'post_views\'] = __( \'views\' ); if(current_user_