Jump to content

Date based conditional


croakingtoad

Recommended Posts

I am starting with three chunks of code wrapped in a <li> and want to order it based on a date in a variable.  Here's what I have for variables in a separate file that is called in with require_once() -

$hkLongDate = "02/25/2008";
$vtLongDate = "02/27/2008";
$totLongDate = "02/29/2008";

 

The code that I want to sort based on the above date is basically three <li> items like below -

$hkList = "<li>Item Blue</li>";
$vtList = "<li>Item Orange</li>";
$totList = "<li>Item Green</li>";

 

I'm just not sure of the best way to associate the var from the first list with the var from the second list and then have it sort by the date value in the first var.

 

Advice?

Link to comment
https://forums.phpfreaks.com/topic/94315-date-based-conditional/
Share on other sites

use strtotime

 

just an example:

<?php
$hkLongDate = strtotime("02/25/2008");
$vtLongDate = strtotime("02/27/2008");
$totLongDate = strtotime("02/29/2008");

if($hkLongDate > $vtLongDate){
     $hkList = "<li>Item Blue</li>";
}elseif($vtLongDate > $hkLongDate){
     $vtList = "<li>Item Orange</li>";
}else{
     $totList = "<li>Item Green</li>";
}
?>

Step #1: Change your dates to UNIX timestamps:

<?php
$hkLongDate = strtotime("02/25/2008");
$vtLongDate = strtotime("02/27/2008");
$totLongDate = strtotime("02/29/2008");
?>

 

Step #2: Create an associative array to tie the elements to their respective times:

<?php
$eles = array(
  array('time' => $hkLongDate, 'item' => $hkList),
  array('time' => $vtLongDate, 'item' => $vtList),
  array('time' => $totLongDate, 'item' => $totList)
);
?>

 

Step #3: Sort the list based on the time and output:

<?php
// Get the columns for multisort
foreach ($eles as $key => $row) {
  $times[$key]  = $row['time'];
  $items[$key] = $row['item'];
}

array_multisort($times, SORT_ASC, $items, SORT_ASC, $eles);

// Check the order:
echo "<pre>\n";
print_r($eles);
echo "</pre>\n";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.