Jump to content

Sort array by folder/tree hierarchy?


nbarone

Recommended Posts

Hi, I have a multidimensional array and I would like to sort it by the length of the first key.

 

The first key is a file path, the second key is a file id, and then several parameters under that.

 

$filelist['\\fileserver\share\path\to\file']['1234']['name'] = "video.avi";

 

If possible, I would like to sort the first key in a tree-like format

example:

$filelist['\\fileserver\share\'] = $filelist[0]

$filelist['\\fileserver\share\folder1'] = $filelist[1]

$filelist['\\fileserver\share\folder1\anotherfolder\'] = $filelist[2]

$filelist['\\fileserver\share\folder1\anotherfolder2\'] = $filelist[3]

$filelist['\\fileserver\share\folder2\'] = $filelist[4]

 

Also, I would like to story the filenames alphabetically

$filelist['\\fileserver\share\path\to\file']['1234']['name'] = "video.avi";

 

I don't know how I would do this all with such a complex array.

 

 

Link to comment
https://forums.phpfreaks.com/topic/193903-sort-array-by-foldertree-hierarchy/
Share on other sites

Use uksort() and uasort() which allows you to define a custom function for sorting an array. I'll make an attempt at the function for you, but what you stated doesn't make sense to me. You state you want to initially sort by the length of the first key, but that doesn't seem correct based upon your example where the last item "folder2" has a shorter key than the item before it - a subfolder under "folder1". I assume you mean to sort the keys alphanumerically. This will take two different sort functions, one for the keys and one for the values of the subarrays.

 

<?php
  

//Sort by file path in primary key
function sort_by_path($a, $b)
{
    return strcasecmp(trim($a, '\\'), trim($b, '\\'));
}
  
//Sort by name sub-element in each path element
function sort_by_filename($a, $b)
{
    return strcasecmp($a['name'], $b['name']);
}
  
uksort($filelist, 'sort_by_path');
  
foreach($filelist as &$path)
{
    uasort($path, 'sort_by_filename');
}
  
?>

 

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.