2

I have a .txt file that store all the information from my form. And I want to have 1 php that display status from the oldest date to today's date.

This is some example of my txt format:

ID4494 (tab("\t")) 12/02/2008 (tab("\t")) ANJAY

ID4496 (tab("\t")) 14/04/2009 (tab("\t")) SONJA

ID4499 (tab("\t")) 19/03/2014 (tab("\t")) BRIAN

and this is my php file

$myfilename = "../idfile/digid.txt";

if( file_exists($myfilename) && filesize($myfilename) > 0 ) {

  $digArray = file($myfilename, FILE_IGNORE_NEW_LINES);

  sort($digArray);

  foreach($digArray as $dig) {

  $oneDigArray = explode("\t", $dig);

  echo "<p>$oneDigArray[0] - $oneDigArray[1] - $oneDigArray[2]</p>";

  }

} else { echo "

There is no Digital ID.

"; }

I tried to use sort ($digArray[1]); since the date is array no. 1. But it wont work.

Any suggestion?

Thank you.

analyticalpicasso
  • 1,993
  • 8
  • 26
  • 45

1 Answers1

1

You can use PHP's usort function and supply your own comparison function. Like this:

function cmp($a, $b)
{
    return ($a[1] > $b[1]) ? 1 : -1;  // Ascending order
    // OR 
    return ($a[1] < $b[1]) ? 1 : -1;  // Descending order
}

usort($digArray, "cmp");

The above will sort your array by date. Here is a test I did.

Test:

$digArray = array(
    array(
        "ID4496", "14/04/2009", "SONJA"
    ),
    array(
        "ID4499", "19/03/2014", "BRIAN"
    ),
    array(
        "ID4494", "12/02/2008", "ANJAY"
    ),
);

function cmp($a, $b)
{
    return ($a[1] > $b[1]) ? 1 : -1;  // Ascending order
}

usort($digArray, "cmp");

print_r($digArray);

Output:

Array ( 
    [0] => Array ( [0] => ID4494 [1] => 12/02/2008 [2] => ANJAY ) 
    [1] => Array ( [0] => ID4496 [1] => 14/04/2009 [2] => SONJA ) 
    [2] => Array ( [0] => ID4499 [1] => 19/03/2014 [2] => BRIAN ) 
)
Joshua Kissoon
  • 3,269
  • 6
  • 32
  • 58
  • thanks for your answer. Can you expalin me why is it 1? – Aurelia Amelinda Apr 20 '14 at 09:58
  • you mean the return 1 and return -1? check the usort php docs, they have full explanations there. Basically 1 means that $a is to be placed before $b in the sorted array, and -1 means the other way around. – Joshua Kissoon Apr 20 '14 at 09:59
  • Yeah, Ive read it. Since my date is array no.1 so it is $a[1]. Ive tried to delete my sort function and replace it with the usort function. But still it doesnt work. It changes the order, but im not quite sure it changes based on which order – Aurelia Amelinda Apr 20 '14 at 10:11
  • Hey @AureliaAmelinda, I don't have your input file, but I did a test with a simulated array, and the output is correct. Check the updated answer to see the test. – Joshua Kissoon Apr 20 '14 at 10:21