2012-04-05 22 views
5

Actualmente tengo un problema dentro de PHP en el que quiero ordenar estas publicaciones por su fecha de creación para que luego puedan mostrarse en orden descendente. He estado buscando una función PHP para hacer esto, pero no he tenido suerte.Ordenando matrices dentro de una matriz en PHP por fecha y hora

¿Existe una solución fácil para esto? Cualquier idea será muy apreciada :)

array 
     0 => 
     array 
      'post_id' => string '1' (length=1) 
      'user_id' => string '3' (length=1) 
      'post' => string 'this is a post' (length=14) 
      'created' => string '2012-04-05 20:11:38' (length=19) 
    1 => 
     array 
      'post_id' => string '2' (length=1) 
      'user_id' => string '2' (length=1) 
      'post' => string 'this is a post' (length=14) 
      'created' => string '2012-04-05 20:11:38' (length=19) 
    2 => 
     array 
      'post_id' => string '3' (length=1) 
      'user_id' => string '5' (length=1) 
      'post' => string 'this is a post' (length=14) 
      'created' => string '2012-04-05 20:11:38' (length=19) 
+4

viene esto una ¿base de datos? ¿Si no, porque no? – NullUserException

+0

desde donde se carga esta matriz? – hjpotter92

+3

Sí, parece sospechosamente filas de consulta de MySQL. 'ORDER BY creado DESC' –

Respuesta

5

Prueba esto:

<?php 
$a=array(
     0 => 
     array(
      'post_id' => '1', 
      'user_id' => '3', 
      'post' => 'this is a post', 
      'created' => '2012-04-05 20:11:40' 
     ), 
    1 => 
     array(
      'post_id' => '2', 
      'user_id' => '2', 
      'post' => 'this is a post', 
      'created' => '2012-04-05 20:11:39' 
     ), 
    2 => 
     array(
      'post_id' => '3', 
      'user_id' => '5', 
      'post' => 'this is a post', 
      'created' => '2012-04-05 20:11:38' 
     ) 
); 
function cmp($a,$b){ 
    return strtotime($a['created'])<strtotime($b['created'])?1:-1; 
}; 

uasort($a,'cmp'); 
print_r($a); 
?> 
+0

'cmp()' debería devolver un valor negativo si '$ a' se considera más pequeño que' $ b', un valor positivo si '$ a' es mayor que' $ b' y 0 si son iguales. – Arjan

+1

gracias, respuesta actualizada (dejé el caso igual, lo sé ...) – stewe

+0

No hay necesidad de 'strtotime'. El formato 'YYYY-MM-DD HH: MM: SS' (24 horas) solo necesita la función' strcmp' para ordenar. – m13r

1

Puede utilizar strtotime() para convertir la marca de tiempo en un número entero.

+2

¿Y cómo va a ayudar esto a ordenar la matriz 2D? –

+0

Heh ok, pregunta vaga. Pensé que OP estaba implicando que sus sellos eran Y-d-m. –

+1

Si las fechas están en formato 'Y-d-m', no puede convertirlas fácilmente en marcas de tiempo. Y si están en formato 'Y-m-d', no necesita convertirlos. – Arjan

1

se puede ordenar una matriz mediante una función de ordenación, así:

function cmp($a, $b) { 
    if($a['created'] < $b['created']) { 
     return 1; 
    } else if ($a['created'] > $b['created']) { 
     return -1; 
    } else { 
     // The only option left is that they are equal 
     return 0; 
    } 
} 

usort($array, cmp); 

Para obtener más información acerca de usort, comprobar el php manpage

+1

Esto producirá un orden ascendente en lugar de descender. – MrCode

+1

Actualicé mi respuesta. Afortunadamente, es solo un pequeño cambio. – Arjan

1

Puede use la función usort() que le permite ordenar una matriz según sus propios criterios.

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

    return ($a['created'] < $b['created']) ? 1 : -1; 
} 

usort($myArray, "cmp"); 

print_r($myArray); 

O si lo desea convertir a un tiempo:

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

    $aInt = strtotime($a['created']); 
    $bInt = strtotime($b['created']); 

    return ($aInt < $bInt) ? 1 : -1; 
} 
2

Ordenamiento de una matriz de registros/assoc_arrays por el campo mysql fecha y hora especificada y por orden:

function build_sorter($key, $dir='ASC') { 
     return function ($a, $b) use ($key, $dir) { 
      $t1=strtotime(is_array($a)?$a[$key]:$a->$key); 
      $t2=strtotime(is_array($b)?$b[$key]:$b->$key); 
      if($t1==$t2) return 0; 
      return (str_to_upper($dir)=='ASC'?($t1 < $t2):($t1 > $t2)) ? -1 : 1; 
     }; 
    } 


    // $sort - key or property name 
    // $dir - ASC/DESC sort order or empty 
    usort($arr, build_sorter($sort, $dir)); 
Cuestiones relacionadas