【问题标题】:array of lists in phpphp中的列表数组
【发布时间】:2011-05-27 07:03:44
【问题描述】:

我想从一个目录中读取所有文件,并将它们存储在一个列表数组中。数组中的键是文件名的起始字母,列表包含以该字母开头的所有名称。

示例: 键“a”可能包含 a1、a2、a3、a4 键'b'可能包含boat.txt、吹嘘.txt、beast.txt

我有文件扫描代码,但对如何在 PHP 中使用数组中的列表感到困惑。你能帮忙吗?

谢谢!

【问题讨论】:

  • 扫码输出什么?文件名?另外,扫描码是递归遍历一个目录中的所有目录吗?
  • PHP 没有“列表”。我想你说的是嵌套数组。

标签: php arrays list


【解决方案1】:

您将需要遍历读取函数返回的列表。如果它是一个数组,你可以像这样迭代(否则,将你的字符串结果分解成一个数组并迭代)。您可以使用数组排序来按字母顺序排列您的数组。

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

?>

【讨论】:

    【解决方案2】:

    感谢大家帮助 php 新手 :-)

    这就是我最终得到的结果:

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

    【讨论】:

      【解决方案3】:
       $first_char = substr($filename, 0, 1); // 'hello.doc' -> 'h'
       $files[$first_char][] = $filename; // add $filename to the $files array under the 'h' key.
      

      【讨论】:

      • 或者对字符串使用数组访问操作符:$string[0]
      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多