我有一个由日期和两个空格后的实际条目组成的聊天记录。现在我需要在输入时对其进行排序,但是当日期相同时,保持条目的顺序相同。
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'
)
我已经尝试过几件事,创建一个在日期中拆分的多维数组,使用几种不同的算法对值进行排序,但我非常确定必须有一些非常简单,明显的方法来做到这一点多圈。
结果应如下所示:
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'
)
答案 0 :(得分:0)
我们可以利用您的日期字符串按正确顺序排序的事实。只需将其用作密钥并执行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 the date and use it as a key. There might be a better regex to use here, but this works...
$aKeyed = array();
foreach($aArray as $value)
{
preg_match('/([0-9]*\/[0-9]* [0-9]*:[0-9]*:[0-9]*\.[0-9]*) (.*)/', $value, $aMatches);
$aKeyed[$aMatches[1]][] = $aMatches[0];
}
// Sort by key.
ksort($aKeyed);
// Iterate the keyed array to get values into the output array. Order is preserved since we appended things to the value of the keyed array in the correct order.
$aOut = array();
foreach($aKeyed as $aValue)
{
foreach($aValue as $value)
{
// Although there are t2 loops, the total number of iterations is the same as the single loop above.
$aOut[] = $value;
}
}
// Print results.
var_export($aOut);
输出:
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',
)