0

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

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

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

4

6 回答 6

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>';
于 2013-10-17T12:50:54.710 回答
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);
于 2013-10-17T12:53:39.907 回答
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);

看到它在行动

于 2013-10-17T12:54:24.260 回答
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 日期函数中生成希望的日期格式..

于 2013-10-17T12:54:12.560 回答
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;
}
于 2013-10-17T13:01:16.883 回答
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);
于 2013-10-17T13:38:38.523 回答