nbarone Posted March 2, 2010 Share Posted March 2, 2010 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. Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 2, 2010 Share Posted March 2, 2010 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'); } ?> Quote Link to comment Share on other sites More sharing options...
nbarone Posted March 2, 2010 Author Share Posted March 2, 2010 Thanks, that worked great. Sorry for the confusion, at first I thought it would be easiest to sort by length, but I figured I'd check and see if it's possible to sort by directory. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.