usort php, order the brazilian table

2

Friends, I have an array with the brazilian table, it contains the team name, victories, balance of goals, goals pro, etc.

I would like to sort the array using the Brazilian criterion, points > victories > goal difference > goals pro > goals against.

If the data was in mysql I would get it.

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

and in the array? any light?

    
asked by anonymous 27.06.2015 / 06:18

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: link

    
27.06.2015 / 10:53