Solved

PHP: Alphabetical with folders on top

Posted on 2011-03-09
3
324 Views
Last Modified: 2012-05-11
I want to sort my array alphabetically, but items without a period in them should be first.

In the example below, I want the items in this order:

Array
(
    [4] => Folder 1
    [2] => Folder 2
    [0] => Apples.jpg
    [3] => Oranges.png
    [1] => Pears.gif
)

<pre><?php

$a = array();

$a[] = 'Apples.jpg';
$a[] = 'Pears.gif';
$a[] = 'Folder 2';
$a[] = 'Oranges.png';
$a[] = 'Folder 1';

asort($a);

print_r($a);

?></pre>

Open in new window

0
Comment
Question by:hankknight
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 39

Accepted Solution

by:
Aaron Tomosky earned 250 total points
ID: 35090409
Split the arrays so folders and files are seperate, sort each array, merge them together
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points
ID: 35090575
It looks like the $a variable that you have handcoded in the example is really the result of reading a directory and aggregating the files and folders that are part of this directory.  Is that right?  If not, please show us where this data comes from.  If so, create two arrays.

You might want to use glob() or readdir() to access the directory.
http://us.php.net/manual/en/function.glob.php
http://us.php.net/manual/en/function.readdir.php

Then you can apply the built-in PHP functions to decide which of the two arrays to put them in.
http://us.php.net/manual/en/function.is-dir.php
http://us.php.net/manual/en/function.is-file.php

Once that is done, sort the two arrays to get the directory and file names in the right order.
http://us.php.net/manual/en/array.sorting.php

Then create the output or combine the arrays in the way that you want.

HTH, ~Ray
0
 
LVL 34

Assisted Solution

by:Beverley Portlock
Beverley Portlock earned 100 total points
ID: 35093346
There is a question I dealt with http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26304778.html to do something very similar. By extending the class and changing the sort criteria it will do what you want.

The altered  version is below. You will need to change the data in the test code at the bottom to try it out on your own folders especially this $pathToStartAt = "/path/to/folder"; line. Put a full path in. I have also inserted a line near the top to enable error_reporting during testing but it can be removed later

<?php

ini_set('display_errors',1); error_reporting(E_ALL);

class FileData {

     public $fileDate;
     public $fileName;
     public $filePath;
     public $fileSize;
     public $folderSort;
     
     function __construct( $p, $n, $d, $s, $t ) {
          $this->filePath = $p;
          $this->fileName = $n;
          $this->size = $s;
          $this->fileDate = $d;
          $this->folderSort = ( strtolower($t) == "file" ) ? 1 : 0;
     }


     function FileCompareSort( $a, $b ) {

          // Build composite keys for sorting
          //
          $aKey = sprintf("%02d%s", $a->folderSort, $a->fileName );
          $bKey = sprintf("%02d%s", $b->folderSort, $b->fileName );

          // Compare
          //
          if ( $aKey < $bKey )
               return -1;
          else
               if ( $aKey > $bKey )
                    return 1;

          return 0;
     }
}



     function searchDir( $pathToDirectory, & $results ) {

          // Make sure the directory has a trailing slash
          //
          if ( substr( $pathToDirectory, -1, 1 ) != "/" )
               $pathToDirectory .= "/";

          // Get list of files in directory
          //
          if ( $fileList = opendir( $pathToDirectory ) ) {
               while ( $aFile = readdir( $fileList ) ) {

                    if ( $aFile == "." || $aFile == ".." )
                         continue;

                    $fileType = filetype( $pathToDirectory . $aFile );
                    if ( $fileType != "file" && $fileType != "dir")
                         continue;

                    // Get attributes and store in array
                    //
                    $dateCreated = filectime( $pathToDirectory . $aFile );
                    $size = filesize( $pathToDirectory . $aFile );

                    $results [] = new FileData( $pathToDirectory, $aFile, $dateCreated, $size, $fileType );
               }

               closedir( $fileList );
          }

          return $results;
     }






$arr = array();
$pathToStartAt = "/path/to/folder";

// Gather data
//
searchDir($pathToStartAt, $arr);

// Sort into sequence
//
uasort( $arr, array( 'Filedata','FileCompareSort') );

// Display as a simple list
//
foreach( $arr as $aFile )  {
     $isDir = ( $aFile->folderSort == 0 ) ? "/" : "";
     
     echo $aFile->filePath . " " . date("m/d/Y", $aFile->fileDate ) . " " . $aFile->size . " " . $isDir.$aFile->fileName . "<br/>";
}


?>

Open in new window


0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
JQuery Search Filter 2 69
How to use session variables in php? 22 46
xml with php question 5 33
PHP $_POST vs asp request 4 23
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
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…
The viewer will learn how to dynamically set the form action using jQuery.

756 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