I have two arrays that filter and order posts by two different custom keys. What I need to do is to merge the arrays and order them by their own custom keys, to not have first a list of the array a and then the list of the array b.
I tried different approaches, but no one really gave me any good result. The last one I tried was usort, but it is basically useless (the two merged arrays were already ordered like this, it only gets the second array first because it doesn't have the first array's custom key).
$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;
First array has a sd_game_series value and sorts first by it, the second one doesn't have the sd_game_series and sorts only by sd_game (sd_game_series is a subset of sd_game, so every post with sd_game_series has also a value in sd_game, but not every sd_game has also a sd_game_series one).
I basically need to sort the two arrays' results alphabetically between each other.
Is it even possible?