php:按时间顺序排序表示日期的字符串数组

时间:2013-10-17 12:45:19

标签: php sorting date

我怎么能转换这个字符串值数组的例子:

$taba=array('12/04/12','13/05/13','03/01/12');

到日期类型值,按照时间顺序对这些日期进行排序,然后在选择选项HTML输入中将它们作为字符串返回?

6 个答案:

答案 0 :(得分:4)

在这里(从过去到未来排序):

$taba=array('12/04/12','13/05/13','03/01/12');
$tabb=array();

foreach ($taba as $key => $val) {
    $d = explode('/', $val);

    $tabb[$key] = $d[2].'-'.$d[1].'-'.$d[0];
}

asort($tabb);

echo '<select>';
    foreach ($tabb as $key => $val) {
        echo '<option value="'.$val.'">'.$taba[$key].'</option>';
    }
echo '</select>';

答案 1 :(得分:3)

作为变体,您可以使用strtotime()将每个元素转换为时间戳,而不是根据需要对输出进行排序和转换。例如:

$taba=array('12/04/12','13/05/13','03/01/12');
usort($taba, function($a, $b){
    $ta = strtotime(str_replace('/', '-', $a));
    $tb = strtotime(str_replace('/', '-', $b));
    if ($ta == $tb) {
        return 0;
    }
    return ($ta < $tb) ? -1 : 1;
});
print_r($taba);

答案 2 :(得分:3)

您可以使用array_map为每个输入日期获取时间戳,然后array_multisort根据相应时间戳的排序顺序重新排序日期:

$taba=array('12/04/12','13/05/13','03/01/12');
$timestamps = array_map(function($d) {
    return DateTime::createFromFormat('d/m/y', $d)->getTimestamp(); }, $taba);
array_multisort($timestamps, $taba);

print_r($taba);

<强> See it in action

答案 3 :(得分:2)

如果您不担心无效日期且所有日期都具有一致的格式,我建议您使用usort自定义比较功能,根据您的需要对日期进行排序,例如:

function cmp($a, $b) {
  $year = strcmp(substr($a, -2), substr($b, -2));
  if ($year == 0) {
    // years are the same, try month
    $month = strcmp(substr($a, 3, 2), substr($b, 3, 2));
    if ($month == 0) {
      return strcmp(substr($a, 0, 2), substr($b, 3, 2));
    }
    return $month;
  }
  return $year;
}

答案 4 :(得分:2)

$taba=array('12/04/12','13/05/13','03/01/12');

usort(
    $taba,
    function ($valueA, $valueB) {
        return preg_replace('#(\d+)\/(\d+)\/(\d+)#', '$3$2$1', $valueA) > 
            preg_replace('#(\d+)\/(\d+)\/(\d+)#', '$3$2$1', $valueB);
    }
);

var_dump($taba);

答案 5 :(得分:2)

$taba=array('12/04/12','13/05/13','03/01/12');
function todate($date){
     // as Legionar comment your date format is wrong .. can't guess which is date, which is year..
     // if year is the last numbers you must change the return to ..
     // return strtotime(implode("-",array_reverse(explode("/",$date))));
     return strtotime(str_replace("/","-",$date));
}

$map = array_map('todate', $taba);
sort($map);
echo "<select>";
foreach($map as $key=>$value) {
    echo '<option>'.date("Y-m-d H:i:s", $value)."</option>";
}
echo "</select>";

抱歉,我错过了排序点。这是排序:) 您可以在foreach日期函数中生成希望的日期格式..