0

致敬,代码长老们,

我正在寻求掌握 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);
}
4

2 回答 2

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()分析文件名。

附言。也不是这个:

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

可以写成

if ( is_dir($file) ) continue; 
于 2012-02-18T12:12:15.120 回答
0

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

于 2012-02-18T12:14:50.020 回答