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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?