Opendir function gives me multiple arrays instead of just one

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-06 12:51:26

问题


Salutations, Elders of code,

I am on a quest to master the spells of PHP, and now need your assistance in slaying a mighty beast.

I'm making a REST API in PHP. One of the functions is a GET that returns a list of pngs in a dir. But instead of returning one array, it returns multiple arrays (one for each iteration?).

I want:

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

But I'm getting:

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

I present my pitiful function for scorn and humiliation:

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

回答1:


You should do some proper indenting and it will be very clear what was wrong. You put the echo json_encode() in the loop. This is a corrected version:

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

Note that this way of checking the extension fails has a minor flaw, in that a file named "png" (with no extension) will match. There are several ways to fix this, e.g. by using pathinfo() to analyse the filename.

ps. also not that this:

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

can be written as

if ( is_dir($file) ) continue; 



回答2:


Think about your loop. You are echoing json_encode($pic_array) every time you loop. so on the first loop all you would have is the first file, then on the second loop... two files get printed. So on and so forth



来源:https://stackoverflow.com/questions/9341025/opendir-function-gives-me-multiple-arrays-instead-of-just-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!