PHP Sort Array (Chatlog) by date (keep order of equivalent dates) -
i have chatlog composed of date , actual entry after 2 spaces. need sort time of entry, keep order of entries same when dates equivalent.
array ( [0] => '6/4 17:01:30.001 x' [1] => '6/4 17:01:30.003 b' [2] => '6/4 17:01:30.003 c' [3] => '6/4 17:01:30.003 a' [4] => '6/4 17:01:30.002 y' )
i tried couple of things, creating multidimensional array splitted in dates values sorting couple of different algorithms i'm pretty sure there must easy, , obvious way without multiple loops.
the result should this:
array ( [0] => '6/4 17:01:30.001 x' [4] => '6/4 17:01:30.002 y' [1] => '6/4 17:01:30.003 b' [2] => '6/4 17:01:30.003 c' [3] => '6/4 17:01:30.003 a' )
we can take advantage of fact date string sort in correct order. use key , ksort:
// starting array $aarray = array( '6/4 17:01:30.001 x', '6/4 17:01:30.002 y', '6/4 17:01:30.003 b', '6/4 17:01:30.003 c', '6/4 17:01:30.003 a' ); // parse out date , use key. there might better regex use here, works... $akeyed = array(); foreach($aarray $value) { preg_match('/([0-9]*\/[0-9]* [0-9]*:[0-9]*:[0-9]*\.[0-9]*) (.*)/', $value, $amatches); $akeyed[$amatches[1]][] = $amatches[0]; } // sort key. ksort($akeyed); // iterate keyed array values output array. order preserved since appended things value of keyed array in correct order. $aout = array(); foreach($akeyed $avalue) { foreach($avalue $value) { // although there t2 loops, total number of iterations same single loop above. $aout[] = $value; } } // print results. var_export($aout);
output:
array ( 0 => '6/4 17:01:30.001 x', 1 => '6/4 17:01:30.002 y', 2 => '6/4 17:01:30.003 b', 3 => '6/4 17:01:30.003 c', 4 => '6/4 17:01:30.003 a', )
Comments
Post a Comment