Opendir 函数为我提供了多个数组,而不是一个
致敬,代码长辈,
我正在寻求掌握 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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你应该做一些适当的缩进,这样就会很清楚出了什么问题。您将
echo json_encode()
放入循环中。这是一个更正的版本:请注意,这种检查扩展名失败的方法有一个小缺陷,即名为“png”(无扩展名)的文件将匹配。有多种方法可以解决此问题,例如使用
pathinfo()
来分析文件名。附:也不是这个:
可以写成
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: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:
can be written as
考虑一下你的循环。每次循环时,您都会回显 json_encode($pic_array) 。所以在第一个循环中,您所拥有的只是第一个文件,然后在第二个循环中......打印两个文件。等等等等
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