php usort, sort table of brasilerão

Asked

Viewed 131 times

2

Friends, I have an array with the Brasileirão table, it contains team name, wins, goal balance, pro goals, etc..

I would like to sort the array using Brasileirão criteria, points > wins > goal balance > goals pro > goals against.

if the data were in mysql I could so.

pts_time DESC, vit_time DESC, sg_time DESC, gp_time DESC, gc_time ASC

and in the array? some light?

1 answer

3


Using the array_multisort function()

Example

/*
pts -> points (pontos)
win -> victories (vitórias)
gd -> goals difference (saldo de gols)
gp -> goals pro (gols pró)
gc -> goals conceded (gols contra)

Cada chave do array $data representa um time.
Para que a função array_multisort() preserve as chaves do array $data, as mesmas devem ser do tipo string.
*/
$data['a'] = array('pts' => 67, 'win' => 7, 'gd' => 2, 'gp' => 10, 'gc' => 8);
$data['b'] = array('pts' => 86, 'win' => 1, 'gd' => 8, 'gp' => 20, 'gc' => 12);
$data['c'] = array('pts' => 85, 'win' => 6, 'gd' => 10, 'gp' => 22, 'gc' => 12);
$data['d'] = array('pts' => 98, 'win' => 2, 'gd' => 5, 'gp' => 15, 'gc' => 10);
$data['e'] = array('pts' => 86, 'win' => 6, 'gd' => 3, 'gp' => 14, 'gc' => 11);
$data['f'] = array('pts' => 67, 'win' => 7, 'gd' => 2, 'gp' => 10, 'gc' => 6);

// Obtendo a lista de colunas baseado no primeiro array.
$arr_keys = array_keys($data['a']);

// Assinando os dados para cada coluna em arrays independentes
foreach ($data as $key => $row) {
    foreach ($arr_keys as $k) {
        $arr[$k][$key]  = $row[$k];
    }
}

// Onde a mágica acontece
array_multisort(
            $arr[$arr_keys[0]], SORT_DESC, SORT_NUMERIC, 
            $arr[$arr_keys[1]], SORT_DESC, SORT_NUMERIC, 
            $arr[$arr_keys[2]], SORT_DESC, SORT_NUMERIC, 
            $arr[$arr_keys[3]], SORT_DESC, SORT_NUMERIC, 
            $arr[$arr_keys[4]], SORT_ASC, SORT_NUMERIC, 
            $data);

// Teste do resultado
print_r($data);

This example was based on one of the documentation examples: http://php.net/array_multisort

  • Thank you very much, I managed to solve with your example, congratulations and again thank you.

  • Friend, realizing this another problem arose, in case of a tie in all conditions, in the table of the Brazilian teams need to be in the same position, for example 7th saints and Corinthians, and not 7th, 8th as the array does, some idea?

  • 1

    add another tiebreaker parameter... what is the CBF criterion for these cases? Yes, add such a criterion.. For Fluminense is called tapeton.. hehehe

Browser other questions tagged

You are not signed in. Login or sign up in order to post.