Opendir函数为我提供了多个数组,而不仅仅是一个 [英] Opendir function gives me multiple arrays instead of just one
问题描述
敬礼,代码长老,
我正在寻求掌握PHP的法术,现在需要您的协助来杀死一头强大的野兽.
I am on a quest to master the spells of PHP, and now need your assistance in slaying a mighty beast.
我正在用PHP制作REST API.函数之一是GET,该GET返回目录中的png列表.但是,它不返回一个数组,而是返回多个数组(每次迭代一个数组?).
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?).
我想要:
["1.png","2.png","3.png"]
但是我得到了:
["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);
}
推荐答案
您应该进行适当的缩进,这很清楚出了什么问题.您将echo json_encode()
放入循环中.这是更正的版本:
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);
}
请注意,这种检查扩展名失败的方式存在一个小缺陷,即匹配名为"png"(无扩展名)的文件.有几种方法可以解决此问题,例如通过使用pathinfo()
分析文件名.
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.也不是这样:
if ( $file=="." || $file==".." || is_dir($file) ) continue;
可以写为
if ( is_dir($file) ) continue;
这篇关于Opendir函数为我提供了多个数组,而不仅仅是一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!