simonp Posted October 1, 2009 Share Posted October 1, 2009 Hi, I'm not great with arrays but need to know if I can include more than just one piece of information? At the moment I'm using this to get a directory list of filenames, sort them into alphabetical order and output them: $narray=array(); $i=0; $dir = new DirectoryIterator( '/home/testing' ); foreach($dir as $file ) { if(!$file->isDot() && !$file->isDir()) { $narray[$i]=$file->getFilename(); $i++; } } sort($narray); for($i=0; $i<sizeof($narray); $i++) { echo "$narray[$i]<br/>"; } BUT I want to also get the file size too using $file->getSize(); I've tried things like: if(!$file->isDot() && !$file->isDir()) { $narray[$i]=$file->getFilename(); $narray[$i]=$file->getSize(); $i++; } But it doesn't like that. I'm asking too much from an array? Cheers Quote Link to comment Share on other sites More sharing options...
SoN9ne Posted October 1, 2009 Share Posted October 1, 2009 This should help if(!$file->isDot() && !$file->isDir()) { $narray[$i]['name']=$file->getFilename(); $narray[$i]['size']=$file->getSize(); $i++; } Quote Link to comment Share on other sites More sharing options...
Psycho Posted October 1, 2009 Share Posted October 1, 2009 With that approach you will need to do something different to sort the array since it is multi-dimensional. Actually I see two possible solutions: 1. If you are only going to use the filesize once (such as when displaying the content of the array), then you don't need to store that info at the time you create the array. You could simply calculate fiel size at the time you generate the content. 2. If you need the filesize data as part of the array, then use SoN9ne's solution to create a multi-dimensional array, then use the following to sort the new array: function sortFileArray($a, $b) { if ($a['name'] == $b['name']) { return 0; } return ($a['name'] < $b['name']) ? -1 : 1; } usort($narray, 'sortFileArray'); Quote Link to comment Share on other sites More sharing options...
simonp Posted October 1, 2009 Author Share Posted October 1, 2009 Thanks guys. I did wonder about the sorting but it seems ok. I'm using: $narray[$i]['name']=$file->getFilename(); $narray[$i]['size']=number_format(($file->getSize()/1024),2)." Kb"; $narray[$i]['date']=date("D d M Y H:i:s",$file->getCTime()); $i++; . . . and just left: sort($narray); as is and it's sorted them ok! Thanks! Quote Link to comment Share on other sites More sharing options...
salathe Posted October 1, 2009 Share Posted October 1, 2009 Rather than manually creating an array of the files, why not just use the iterator_to_array function to do the hard work for you? Of course that would include dots/directories too, but a quick filter would sort that out. 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.