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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度