dtng25909 2015-06-04 15:06
浏览 46
已采纳

按日期排序PHP排序数组(Chatlog)(保持等效日期的顺序)

I have a chatlog composed of a date and the actual entry after two spaces. Now I need to sort this by the time of the entry, but keep the order of the entries the same when the dates are 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 already tried a couple of things, creating a multidimensional array splitted in the dates an values sorting with a couple of different algorithms but I'm pretty sure there must be some really easy, and obvious way to do this without multiple loops.

The result should look like 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'
)
  • 写回答

1条回答 默认 最新

  • doulang2311 2015-06-04 15:58
    关注

    We can take advantage of the fact that your date string will sort in the correct order. Just use that as a key and do a 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);
    

    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',
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀