2012-07-29 8 views
5

Tengo la siguiente matriz:varias ordenaciones en un arsenal

Array 
(
[0] => Array 
    (
     [note] => test 
     [year] => 2011 
     [type] => football 
    ) 

[1] => Array 
    (
     [note] => test1 
     [year] => 2010 
     [type] => basket 
    ) 

[2] => Array 
    (
     [note] => test2 
     [year] => 2012 
     [type] => football 
    ) 

[3] => Array 
    (
     [note] => test3 
     [year] => 2009 
     [type] => basket 
    ) 

[4] => Array 
    (
     [note] => test4 
     [year] => 2010 
     [type] => football 
    ) 

) 

Y quisiera ordenar primero que según otra matriz por tipo:

Por ejemplo: $sort = array('football','basket');

Y después por año.

¿Cómo puedo hacer eso?

Gracias.

salida deseada debe ser:

Array 
(
[2] => Array 
    (
     [note] => test2 
     [year] => 2012 
     [type] => football 
    ) 
[0] => Array 
    (
     [note] => test 
     [year] => 2011 
     [type] => football 
    ) 
[4] => Array 
    (
     [note] => test4 
     [year] => 2010 
     [type] => football 
    ) 

[1] => Array 
    (
     [note] => test1 
     [year] => 2010 
     [type] => basket 
    ) 

[3] => Array 
    (
     [note] => test3 
     [year] => 2009 
     [type] => basket 
    ) 

) 

no me importa si restablecer los valores de índice.

Gracias.

Respuesta

2

Uso array_multisort. Asumiendo que su matriz es $arr:

foreach($arr as $key=>$row) { 
    $type[$key] = $row['type']; 
    $year[$key] = $row['year']; 
} 
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr); 

utilizar una matriz addictional especificar el tipo de orden, que podría hacer:

$sortBy = array('football','basket'); 
foreach($arr as $key=>$row) { 
    $type[$key] = array_search($row['type'],$sortBy); 
    $year[$key] = $row['year']; 
} 
array_multisort($type, SORT_ASC, $year, SORT_ASC, $arr); 

Ejemplo enlace:

http://codepad.org/qhZCpbZE

+0

Gracias amigo parece que funciona. ¿Pero cómo puedo incluir la matriz $ sortBy también? – glarkou

+0

@salamis Edité mi respuesta para cubrir eso también. – lafor

+0

Gracias amigo parece que funciona como se esperaba. una pregunta rápida. ¿Por qué seguimos usando '$ type, SORT_ASC' si estamos ordenando por otra matriz? – glarkou

1

Uso

function byType($a, $b) 
{ 
    if ($a['type'] == $b['type']) { 
     return 0; 
    } 

    foreach(array('football','basket') as $type) { 
     if ($a['type']=$type) return -1; 
     if ($b['type']=$type) return 1; 
    } 

    return 0; 
} 


function byYear($a, $b) 
{ 
    if ($a['year'] == $b['year']) { 
     return 0; 
    } 
    return ($a['year'] < $b['year']) ? -1 : 1; 
} 

usort($array,"byType"); 
usort($array,"byYear"); 
+0

No está funcionando mate. Primero porque no puedo usar otra matriz para ordenar por tipo. Y en segundo lugar, cuando se realiza el segundo uso, todo vuelve a mezclarse. Por favor, consulte: http://codepad.org/PO3CvGsu y el resultado deseado. Me gustaría que la clasificación por año solo suceda si el tipo es el mismo. – glarkou

+0

ESTÁ FUNCIONANDO. http://codepad.org/PwYKyyMS – Adi

+0

@Adnan No funciona, cambie la matriz, actualmente funciona por "suerte" – Leigh

4

requiere una versión de PHP que admite cierres cuando se ejecuta como está

Su matriz secundaria se puede definir fuera del género en sí. Si no puede admitir cierres, esto puede colocarse directamente en la rutina de clasificación.

$sortBy = array('football', 'basket'); 

Sort routine.

Ordena por año si los tipos son los mismos, y ordena según los tipos en su matriz $sortBy en caso contrario.

usort($a, function($a, $b) use ($sortBy) { 
    if ($a['type'] == $b['type']) { 
     return ($b['year'] - $a['year']); 
    } 
    $typeOrder = array_flip($sortBy); 
    return $typeOrder[$a['type']] - $typeOrder[$b['type']]; 
}); 
+0

¿Cómo puedo usar esto? Intenté http://codepad.org/HCodcfgl pero no parece funcionar mate. Gracias por tu ayuda. – glarkou

+0

@salamis Codepad es PHP 5.2, que tiene 6 años y no admite cierres. ¿Qué versión de PHP usa ** usted **? (También puede usar [el teclado de Viper 7] (http://codepad.viper-7.com/MpTYaB)) – Leigh

Cuestiones relacionadas