普通网友 2015-12-18 18:14
浏览 27
已采纳

sort()具有更改值的多维数组

I want sorting multidimensional array. But I must to change format value to sorting before then get back format in beginning.

This my array (multidimensional)

$db = [['1','00:01:13.145'], ['2','00:02:19.145'],
       ['3','00:02:13.235'], ['4','00:01:44.020'], 
       ['5','00:02:25.035'], ['6','00:01:11.031']];

For example can help you to answer, I Know a part how to sorting array time and to get format back again:

This my array (single)

$db2 = ['00:01:13.145','00:02:19.145',
        '00:02:13.235','00:01:44.020', 
        '00:02:25.035','00:01:11.031'];

Function to sorting this

$rep = str_replace(':','', str_replace('.','', $db2));
echo arr($rep);

function arr($array) {
    $return = array();
    foreach($array as $row) {
        $return[] = (int)$row;
        sort($return);
    }
    return $return;
}

The output will be

Array ( [0] => 111031 [1] => 113145 [2] => 144020 [3] => 213235 [4] => 219145 [5] => 225035 )

Second, I know how to get format again, example:

$int = 111031;
$str = substr_replace(substr_replace($int,".",-3,-3),":",-6,-6);
echo substr_replace($str,'00:0',-9,-9);

from (int)111031 the output will be 00:01:11.031

Pleas help me to solve this

  • 写回答

1条回答 默认 最新

  • dsghpgmay31938863 2015-12-18 18:24
    关注

    This should work for you:

    Here we simply use usort() to use our own custom compare function. In this function we first explode() the time by a dot, so we get the time and the milliseconds separately. After this we convert the time into a timestamp with strtotime() and multiply it by 1,000 so we can add the milliseconds to it.

    With this we have converted the time into milliseconds and we can simply compare the numbers and sort by the milliseconds.

    Code:

    <?php
    
        $db = [
                  ['1','00:01:13.145'], ['2','00:02:19.145'],
                  ['3','00:02:13.235'], ['4','00:01:44.020'], 
                  ['5','00:02:25.035'], ['6','00:01:11.031']
              ];
    
    
        usort($db, function($a, $b){
            list($timeOne, $millisecondsOne) = explode(".", $a[1]);
            list($timeTwo, $millisecondsTwo) = explode(".", $b[1]);
    
            $millisecondsOne = strtotime($timeOne) * 1000 + $millisecondsOne;
            $millisecondsTwo = strtotime($timeTwo) * 1000 + $millisecondsTwo;
    
            if($millisecondsOne == $millisecondsTwo)
                return 0;
            return $millisecondsOne > $millisecondsTwo ? 1 : -1;
    
       });
    
        print_r($db);
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应