【问题标题】:Opendir function gives me multiple arrays instead of just oneOpendir 函数给了我多个数组而不是一个
【发布时间】:2012-02-18 12:09:30
【问题描述】:

致敬,代码长老,

我正在寻求掌握 PHP 的法术,现在需要你的帮助来杀死一只强大的野兽。

我正在用 PHP 制作一个 REST API。其中一个函数是 GET,它返回目录中的 png 列表。但它不是返回一个数组,而是返回多个数组(每次迭代一个?)。

我想要:

["1.png","2.png","3.png"]

但我得到了:

["1.png"]["1.png","2.png"]["1.png","2.png","3.png"]

我以轻蔑和羞辱的方式表现出我可怜的功能:

function getPics() {
$pic_array = Array(); 
$handle =    opendir('/srv/dir/pics'); 
while (false !== ($file = readdir($handle))) { 
    if ($file!= "." && $file!= ".." &&!is_dir($file)) { 
    $namearr = explode('.',$file); 
    if ($namearr[count($namearr)-1] == 'png') $pic_array[] = $file; 
    } 
echo json_encode($pic_array);
} 
closedir($handle);
}

【问题讨论】:

    标签: php arrays rest opendir


    【解决方案1】:

    你应该做一些适当的缩进,它会很清楚哪里出了问题。您将echo json_encode() 放入 循环中。这是一个修正版:

    function getPics()
    {
        $pic_array = Array(); 
        $handle = opendir('/srv/dir/pics'); 
        while ( false !== ($file = readdir($handle)) )
        {
            if ( $file=="." || $file==".." || is_dir($file) ) continue; 
            $namearr = explode('.',$file);
            if ($namearr[count($namearr)-1] == 'png') $pic_array[] = $file; 
        } 
        echo json_encode($pic_array);
        closedir($handle);
    }
    

    请注意,这种检查扩展失败的方法有一个小缺陷,即会匹配名为“png”(没有扩展名)的文件。有几种方法可以解决这个问题,例如通过使用pathinfo() 来分析文件名。

    ps。也不是这样:

    if ( $file=="." || $file==".." || is_dir($file) ) continue; 
    

    可以写成

    if ( is_dir($file) ) continue; 
    

    【讨论】:

    • 非常感谢您的指正和提示。今后我将坚持适当的缩进。
    【解决方案2】:

    想想你的循环。每次循环时,您都在回显 json_encode($pic_array) 。所以在第一个循环中,您将拥有的只是第一个文件,然后在第二个循环中......两个文件被打印出来。等等等等

    【讨论】:

    • 谢谢! json_encode 现在在循环之外,并且正确地只返回一个数组。
    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 1970-01-01
    • 2017-01-25
    相关资源
    最近更新 更多