[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Sorting one array by another

Posted on 2006-03-28
10
Medium Priority
?
280 Views
Last Modified: 2012-06-21
Hi There.

I have the below source:

       //settings
      $path = "/home/mydida/public_html/swfpres/pres/";
      
      // Open the folder
      $dir_handle = @opendir($path);

      //get arrays
      $num = 0;
      while ($file1 = readdir($dir_handle)) {
            $filearray[$num] = $file1;
            $datearray[$num] = filemtime($path.$file1);
            $num++;
      }
      
      //sort file array
      //FIND OUT HOW!!!!!
      
      // Loop through the files
      foreach ($filearray as $key => $file) {

            //get rid of rubbish
            if($file == "." || $file == ".." || $file == "index.php" ) { continue; }
            
            
            print "<a href='".$PHP_SELF."?view=".$file."'>";
            if(!@file_get_contents("pres/".$file."/pres.txt")){
                  print $file." - No details detected!";
            }else{
                  $contents = explode("&*|*&",file_get_contents("pres/".$file."/pres.txt"));
                  print $contents[0];
            }
            print "</a>";
            print " Date = ".date('F d, Y', $datearray[$key])."<br />";

      }

      // Close
      closedir($dir_handle);

Basically, you will see that I created the array "datearray" and the array "filearray". I need to be able to sort the array "filearray", using the values provided by "datearray", without changing the "filearray".

EG: datearray contains values - "12 December 2001", "14 December 2003", "26 February 1999". And filearray contains values "hi1.txt","hi2.txt","hi3.txt".
I would want it to sort the array filearray to be sorted descending according to values in datearray (the keys of both arrays tally up) - "hi2.txt","hi1.txt","hi3.txt".

I am sure there is a way to do this, I just cant find the right way looking on the internet.

Thanks for your time!

Giles Williams.
0
Comment
Question by:gileze33
  • 3
  • 3
  • 3
  • +1
10 Comments
 
LVL 49

Expert Comment

by:Roonaan
ID: 16314111
Easier would be to have a single array holding (date, file) tuples:

 while ($file1 = readdir($dir_handle)) {
          $filearray[$num] = array('file'=> $file1, 'date' => filemtime($path.$file1));
          $num++;
     }

Then you can use usort, to sort the array:

usort($filearray, 'mysort');
function mysort($item1, $item2) {
  return strcmp($item1['file'], $item2['file']);
}

-r-
0
 
LVL 3

Author Comment

by:gileze33
ID: 16314143
Hi There. Thanks for fast response.

If I did this, how would I then get the values for date and file out from array while in my foreach loop?

Thanks.
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 16314199
foreach ($filearray as $key => $fileinfo) {
   $file = $fileinfo['file'];
   $date = $fileinfo['date'];

-r-
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 3

Author Comment

by:gileze33
ID: 16314282
I did that got this error:
Warning: usort(): Invalid comparison function. in /home/mydida/public_html/swfpres/index.php on line 18

Source Again:

      //settings
      $path = "/home/mydida/public_html/swfpres/pres/";
      
      // Open the folder
      $dir_handle = @opendir($path);

      //get arrays
      $num = 0;
      while ($file1 = readdir($dir_handle)) {
          $filearray[$num] = array('file'=> $file1, 'date' => filemtime($path.$file1));
          $num++;
    }
      
      //sort file array
      usort($filearray, 'mysort');
            function mysort($item1, $item2) {
            return strcmp($item1['file'], $item2['file']);
      }
      
      // Loop through the files
      foreach ($filearray as $key => $fileinfo) {
            
            //set values
            $file = $fileinfo['file'];
               $date = $fileinfo['date'];
            
            //get rid of rubbish
            if($file == "." || $file == ".." || $file == "index.php" ) { continue; }
            
            
            print "<a href='".$PHP_SELF."?view=".$file."'>";
            if(!@file_get_contents("pres/".$file."/pres.txt")){
                  print $file." - No details detected!";
            }else{
                  $contents = explode("&*|*&",file_get_contents("pres/".$file."/pres.txt"));
                  print $contents[0];
            }
            print "</a>";
            print " ".date('F d, Y', $date)."<br />";

      }

      // Close
      closedir($dir_handle);
0
 
LVL 37

Expert Comment

by:Harisha M G
ID: 16316926
How about this:

array_multisort($datearray, SORT_DESC, SORT_NUMERIC, $filearray);


Ex:

<?php
      $filearray = array("hi1.txt","hi2.txt", "hi3.txt");
      $datearray = array(strtotime("12 December 2001"), strtotime("14 December 2003"),strtotime( "26 February 1999"));

      var_dump($filearray);
      var_dump($datearray);

      
      array_multisort($datearray, SORT_DESC, SORT_NUMERIC, $filearray);

      var_dump($filearray);
      var_dump($datearray);
?>
0
 
LVL 6

Accepted Solution

by:
Brian Bush earned 2000 total points
ID: 16318203
How about this:

<?php

$_path = "c:\\";
$_dir_handle = @opendir($_path);

$_i = 0;
while ($_file = readdir($_dir_handle)) {
     $_files[$_i] = array('file' => $_file, 'date' => filemtime($_path . $_file));
     $_i++;
}

function cmp($a, $b) {
     return strcmp(strtoupper($a['file']), strtoupper($b['file']));
}

//sort file array
usort($_files, "cmp");

foreach ($_files as $_key => $_value) {

     //get rid of rubbish
    if ($_value['file'] == "." || $_value['file'] == ".." || $_value['file'] == "index.php") {
        continue;
    }

    echo "<a href='" . $_SERVER['PHP_SELF'] . "?view=" . $_value['file'] . "'>";

    if(!@file_get_contents("pres/" . $_value['file'] . "/pres.txt")) {
        echo $_value['file'] . " - No details detected!";
    } else {
        $_contents = explode("&*|*&", file_get_contents("pres/" . $_value['file'] . "/pres.txt"));
        echo $_contents[0];
    }

    echo "</a> " . date('F d, Y', $_value['date']) . "<br />";
}

// Close
closedir($_dir_handle);

?>

I threw in a strtoupper in the cmp function to make the listing case-insensitive.
--brian
0
 
LVL 6

Expert Comment

by:Brian Bush
ID: 16318208
oh yeah, I made the path="C:\\" so I could test it on my laptop.
--brian
0
 
LVL 3

Author Comment

by:gileze33
ID: 16318579
theonlygoodisknowledge

Seems to work, but is it neccessary to have variables as $_variable?, as this mucks up code sent to other pages.

Giles.
0
 
LVL 6

Expert Comment

by:Brian Bush
ID: 16318636
Nope. It's just a naming convention I use for private variables.
You can name them anything you want.

--brian
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 16318659
Hi gileze33, try this function for the mysort. strcmp doesn't work as I though it would.

     //sort file array
     function mysort($item1, $item2) {
          if($item1['file'] == $item2['file']) return 0;
          return strcmp($item1['file'], $item2['file']) > 0 ? 1 : -1;
     }
     usort($filearray, 'mysort');
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
This article discusses how to implement server side field validation and display customized error messages to the client.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Suggested Courses
Course of the Month20 days, 14 hours left to enroll

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question