Jump to content

Help needed with array


simonp

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/176193-help-needed-with-array/
Share on other sites

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');

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!

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.