Support Meta Box Group Sort group array value to rank Reply To: Sort group array value to rank

#13098
Anh TranAnh Tran
Keymaster

Hi Arif,

This is more related to sorting values in PHP rather than with Meta Box. I'll try to give you the concept of doing that, please follow it. Your logic is complicated and I couldn't provide full code for you.

As I see you store all teams and their info in a group field goalkick_league_point_table_option, right? And for each team, you record the number of matches that the team won or lost, right? (I assume that, cause I don't know if that's the number of matches or number of scores for matches).

To sort teams, we will need to use usort() function.

Here is my first idea for sorting by scores:

function get_score( $team_details ) {
    $win = isset( $team_details['goalkick_league_standing_match_win_manual'] ) ? $team_details['goalkick_league_standing_match_win_manual'] : 0;
    $lost = isset( $team_details['goalkick_league_standing_match_win_manual'] ) ? $team_details['goalkick_league_standing_match_loss_manual'] : 0;
    return $win * 3;
}

$teams = rwmb_meta( 'goalkick_league_point_table_option' );
usort( $teams, function( $a, $b ) {
    $a_score = get_score( $a );
    $b_score = get_score( $b );
    
    if ( $a_score == $b_score ) {
        return 0;
    }
    return $a_score > $b_score ? -1 : 1;
} );

If you want to check by other conditions (2 and 3), then in the callback function of usort, add more conditions, like this:

usort( $teams, function( $a, $b ) {
    $a_score = get_score( $a );
    $b_score = get_score( $b );
    
    // Scores equal, sort by matches played.
    if ( $a_score == $b_score ) {
        $a_matches = get_matches( $a );
        $b_matches = get_matches( $b );

        // If matches equal, sort by something else.
        if ( $a_matches == $b_matches ) {
        }

        return $a_matches > $b_matches ? -1 : 1;
    }
    return $a_score > $b_score ? -1 : 1;
} );