Jump to content

Sorting an array by date.


iPixel

Recommended Posts

So i've got a CSV file, pull data from it and it's stored within an array. $data[0] contains date that looks like so 9/14/2011 00:00:00. How can i sort this array before displaying it so that it's sorted by Date ASC by default.

 

<?php
if (($handle = fopen("http://www.website.com/images/uploads/Recruitment_for_Web.csv", "r")) !== FALSE) 
{
	while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) 
		{
			echo '<tr>';
			echo '<td>' . str_replace("0:00:00","",$data[0]) . '</td>';
			echo '<td>' . $data[1] . '</td>';
			echo '<td>' . $data[2] . '</td>';
			echo '<td>' . $data[3] . '</td>';
			echo '<td>' . $data[4] . '</td>';
			echo '<td>'; 
			if($data[7] != "")
				{
					echo '<a href="' . $data[7] . '" target="_blank">' . $data[5] . '</a>';
				}
			else
				{
					echo $data[5];	
				}
			echo '</td>';
			echo '<td>' . $data[6] . '</td>';
			echo '</tr>';
		   
		}
	fclose($handle);
}
?>

 

Thanks

Link to comment
Share on other sites

I don't know the exact code, but I know there are PHP functions that allow you to make a variable into a 'date' variable, so PHP will recognize it as a date, and not as a strings of characters. After that you might be able to do some sorting using greater-then, less-then etc, but I'm really not too sure on that..

Link to comment
Share on other sites

Is there any way you can change the input format so the date is in the proper format (YYYY-MM-DD)?  If you do, then string sorting will work just fine.

 

If not, you'll have to pre-process this list so that the date is in that proper format (using explode or substr) and then re-create it into a sortable format (either a timestamp or YYYY-MM-DD).

 

-Dan

Link to comment
Share on other sites

This is not tested, so there may be some syntax or minor errors, but the logic is sound

//Function to add timestamp (and remove hours from date)
function addtimestamp(&$record)
{
    $record['timestamp'] = strtotime($record[0]);
    $record[0] =  str_replace('0:00:00', '', $record[0]);
}

//Function to sort array
function sortbytimestamp($a, $b)
{
    if ($a['timestamp'] == $b['timestamp']) { return 0; }
    return ($a['timestamp'] < $b['timestamp']) ? -1 : 1;
}

//Define the source of file
$fileSrc = "http://www.website.com/images/uploads/Recruitment_for_Web.csv";
//Read file into an array
$data = file($fileSrc);

if($data!=false)
{
    //Add a timestamp value to each record
    array_walk($data, 'addtimestamp');

    //Sort the array using custom function
    usort($data, 'sortbytimestamp');

    //Output the data
    foreach($data as $record)
    {
        $link = (!empty($data[7])) ? "<a href='{$data[7]}' target='_blank'>{$data[5]}</a>" : $data[5];
        echo "<tr>\n";
        echo "<td>{$data[0]}</td>\n";
        echo "<td>{$data[1]}</td>\n";
        echo "<td>{$data[2]}</td>\n";
        echo "<td>{$data[3]}</td>\n";
        echo "<td>{$data[4]}</td>\n";
        echo "<td>{$link}</td>\n"; 
        echo "<td>{$data[6]}</td>\n";
        echo "</tr>\n";
    }
}

 

EDIT: It looks like the forum parsing messed up the value for $fileSrc, so just make sure you correct it before trying it.

 

EDIT#2: I notice your logic for removing the hours from the display date only removes a single zero for the hour, but you stated that there are two zeros for the hour. I would also think you would want to removing the space before the time component. I used your same logic, but I would think the appropriate replacement would be

$record[0] =  str_replace(' 00:00:00', '', $record[0]);

Link to comment
Share on other sites

I went ahead and tested against some mock data and found a couple issues. This is fixed and should work if your data is in the format you say it is:

//Function to add timestamp (and remove hours from date)
function addtimestamp(&$record)
{
    $record['timestamp'] = strtotime($record[0]);
    $record[0] =  str_replace(' 00:00:00', '', $record[0]);
}

//Function to sort array
function sortbytimestamp($a, $b)
{
    if ($a['timestamp'] == $b['timestamp']) { return 0; }
    return ($a['timestamp'] < $b['timestamp']) ? -1 : 1;
}

//Define the source of file
$fileSrc = "http://www.website.com/images/uploads/Recruitment_for_Web.csv";
//Read file into an array
$data = file($fileSrc);

if($data!=false)
{
    //Add a timestamp value to each record
    array_walk($data, 'addtimestamp');

    //Sort the array using custom function
    usort($data, 'sortbytimestamp');

    //Output the data
    echo "<table border='1'>\n";
    foreach($data as $record)
    {
        $link = (!empty($record[7])) ? "<a href='{$record[7]}' target='_blank'>{$record[5]}</a>" : $record[5];
        echo "<tr>\n";
        echo "<td>{$record[0]}</td>\n";
        echo "<td>{$record[1]}</td>\n";
        echo "<td>{$record[2]}</td>\n";
        echo "<td>{$record[3]}</td>\n";
        echo "<td>{$record[4]}</td>\n";
        echo "<td>{$link}</td>\n"; 
        echo "<td>{$record[6]}</td>\n";
        echo "</tr>\n";
    }
    echo "</table>\n";
}

Link to comment
Share on other sites

This should do the trick.  Not tested though. 8)

<?php
function mydatesort($a, $b){
    global $data;
    return strcmp($data[$a][0], $data[$b][0]);
}

function format_date(&$mydata){
$format = 'Y-m-d';
foreach($mydata as &$d){
	$d[0] = date($format, strtotime($d[0]));
}
}

if (($handle = fopen("http://www.website.com/images/uploads/Recruitment_for_Web.csv", "r")) !== FALSE) 
{
	// format the date first
	format_date($data);
	// Next we sort the table by date
	uksort($data, 'mydatesort');
	while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) 
		{
			echo '<tr>';
			echo '<td>' . $data[0] . '</td>';
			echo '<td>' . $data[1] . '</td>';
			echo '<td>' . $data[2] . '</td>';
			echo '<td>' . $data[3] . '</td>';
			echo '<td>' . $data[4] . '</td>';
			echo '<td>'; 
			if($data[7] != "")
				{
					echo '<a href="' . $data[7] . '" target="_blank">' . $data[5] . '</a>';
				}
			else
				{
					echo $data[5];	
				}
			echo '</td>';
			echo '<td>' . $data[6] . '</td>';
			echo '</tr>';
		   
		}
	fclose($handle);
}
?>

Link to comment
Share on other sites

This should do the trick.

 

Nope

if (($handle = fopen("http://www.website.com/images/uploads/Recruitment_for_Web.csv", "r")) !== FALSE) 
{
	// format the date first
	format_date($data);
	// Next we sort the table by date
	uksort($data, 'mydatesort');
	while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) 
		{

 

How can you run format_date($data) before you have even defined $data? $data, in that code, represents one record, so you couldn't run the format_date() function on it anyway. Also, why would you use uksort() with global $data; in the sorting function so you can compare the values? Just use usort() and don't use global().

 

Plus, the OP never stated he wanted to change the format of the displayed date.

Link to comment
Share on other sites

u know, ur right mj, I was so focused on the sort, that forgot to read the rest of the code, but hey, it's like I said, i didn't even test it.    And looking through your logic, it's basically the same thing, except I forgot to fill in an array with the files information, and also, you compared it directly, and I compared it using strcmp(); 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.