开发者

array of lists in php

开发者 https://www.devze.com 2023-01-31 16:53 出处:网络
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 l

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!


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


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>";

?>


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

精彩评论

暂无评论...
验证码 换一张
取 消