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

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.