是否可以在php中对数组进行排序以获得给定的输出?

时间:2015-01-30 14:33:20

标签: php sorting

我有一个数组。

$arr = array('10min', '25min', '35 min', '1 hour', '10-20min', '2 hours', '25-30min', '2-2 1/2 hours', '45min' );

我需要按以下顺序输出。
10分钟
10-20分钟
25分钟
25-30min
35分钟
45分钟
1小时
2小时
2-2 1/2小时

是否有可能进入PHP?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用此代码执行此操作:)

<?php

        $arr = array('10min', '25min', '35 min', '1 hour', '10-20min', '2 hours', '25-30min', '2-2 1/2 hours', '45min');
        $m = [];
        $h = [];

        foreach ($arr as $a) {
            if (strpos($a,"min")) $m[] = $a;
            elseif(strpos($a,"hours") || strpos($a,"hour")) $h[] = $a;
        }

        foreach ($m as &$mm) $mm = str_replace("-","zzz",$mm);
        foreach ($h as &$hh) $hh = str_replace("-","zzz",$hh);

        natsort($m);
        natsort($h);

        foreach ($m as &$mm) $mm = str_replace("zzz","-",$mm);
        foreach ($h as &$hh) $hh = str_replace("zzz","-",$hh);

        $a = array_merge($m,$h);
        print_r($a);

?>

答案 1 :(得分:0)

<?php

$arr = array('10min', '25min', '35 min', '1 hour', '10-20min', '2 hours', '25-30min', '2-2 1/2 hours', '45min' );
echo $arr['0'], "<br>";
echo $arr['4'], "<br>";
echo $arr['1'], "<br>";
echo $arr['6'], "<br>";
echo $arr['8'], "<br>";
echo $arr['3'], "<br>";
echo $arr['5'], "<br>";
echo $arr['7'], "<br>";
?>

如果那是你想要做的,那么你去吧,如果你要求这样的东西作为例子..         使用foreach()