2012-02-18 124 views
0

拜,代碼長老,執行opendir功能讓我多陣列,而不只是一個

我在尋求掌握PHP的法術,現在需要在殺害你的幫助一個強有力的野獸。

我正在PHP中創建一個REST API。其中一個函數是一個GET,它返回一個dir中的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); 
} 

回答

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; 
+0

非常感謝您的糾正和提示。我將從此堅持正確的縮進。 – playeren 2012-02-18 12:43:06

0

想想你的循環。每次循環時都會回顯json_encode($ pic_array)。所以在第一個循環中,您只需要第一個文件,然後在第二個循環中打印兩個文件。等等等等

+0

謝謝! json_encode現在在循環之外,並且恰好只返回一個數組。 – playeren 2012-02-18 12:44:00

相關問題