how could i convert this exemple of string values array:
$taba=array('12/04/12','13/05/13','03/01/12');
to date type values, sort these dates chronogically before returning them as strings in a select option HTML input ?
$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>";
Sorry I missed the sort point. Here is with sorting :) You can generate the wished date format at the foreach date function..
Here you are (sorted from past to the future):
$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>';
As variant, you can use strtotime()
for converting each element to timestamp, than sort how you need and transform back before output. Example:
$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);
You can use array_map
to get a timestamp for each input date, then array_multisort
to reorder the dates based on the sorted order of the corresponding timestamps:
$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);
If you're not worried about invalid dates and all dates have a consistent format, might I suggest you use usort with a custom compare function that sorts the dates however you wish e.g.:
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;
}
$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);