N. Ysgerrig
N. Ysgerrig

Reputation: 21

array of lists in php

I would like to read all files from a directory, and store them in an array of lists. The keys in the array is the starting letter of the filename, and the list contains all names starting with that letter.

Example: key 'a' may contain a1, a2, a3, a4 key 'b' may contain boat.txt, boast.txt, beast.txt

I have the file scan code in place, but am confused about how to use lists in an array in PHP. Can you help with that?

Thanks!

Upvotes: 1

Views: 3408

Answers (3)

RageD
RageD

Reputation: 6823

You will want to iterate through the list returned by your read function. If it's an array you can iterate like this (otherwise, explode your string results into an array and iterate through). You can use array sorts to alphabetize your arrays.

<?php

$somelist = array("awesomeness", "stupidness", "funniness", "alotness", "lolz0rz", "sorryness");
$newlist = array();

foreach($somelist as $val)
{
    $newlist[substr($val,0,1)][] = $val;
}

print "<pre>";
print_r($newlist);
print "</pre>";

?>

Upvotes: 3

N. Ysgerrig
N. Ysgerrig

Reputation: 21

Thanks all for helping a php newbie :-)

Here's what I ended up with:

$dirname = "./filesdir/";
$dh = opendir( $dirname ) or die("Couldn't open directory [".$dirname."]");
$arr = array();
while ( ! ( ( $file = readdir( $dh ) ) === false) ) 
{
    if( $file != "." && $file != ".." )
    {
        if ( !is_dir("$dirname/$file" ) && substr_count($file, '.') == 1 )
        {
            $ext = strstr($file, '.', true);
            $key = substr($ext,0,1);

            if( $key < 'a' || $key > 'z' )
            {
                $key="other";
            }
            $arr[$key][] = $ext;
        }
    }
}
closedir( $dh );
print_r($arr);

Upvotes: 1

Marc B
Marc B

Reputation: 360702

 $first_char = substr($filename, 0, 1); // 'hello.doc' -> 'h'
 $files[$first_char][] = $filename; // add $filename to the $files array under the 'h' key.

Upvotes: 2

Related Questions