2017-10-21 90 views
0

以下函數返回空字符串。有人可以建議下面的代碼有什麼問題嗎?我正在對此函數進行AJAX調用。對Wordpress函數的Ajax調用返回空數組

function LoadImagesForMenus() { 

    $filenameArray = []; 
    $validextensions = ["gif", "jpg", "jpeg", "png"]; 
    $handle = opendir(get_template_directory().'/analyzer-images/'); 

    while ($file = readdir($handle)) { 
     if ($file !== '.' && $file !== '..' && !empty($file)) { 
      $filenameArray[] = $file; 
      $ext = pathinfo($file, PATHINFO_EXTENSION); 
      if (in_array($ext, $validextensions)) { 
       $fileArray = []; 
       $fileArray["fileName"] = "http://xn--ernhrungsberaterzrich-71b08c.ch/wp-content/themes/abundance/analyzer-images/$file"; 
       list($width, $height) = getimagesize("/home/httpd/vhosts/xn--ernhrungsberaterzrich-71b08c.ch/httpdocs/wp-content/themes/abundance/analyzer-images/$file"); 
       $fileArray["width"] = $width; 
       $fileArray["height"] = $height; 
       if ($width !== null && $height !== null) { 
        array_push($filenameArray, $fileArray); 
       } 
      } 
     } 
    } 
    echo json_encode($filenameArray); 
    exit(0); 
} 

感謝

+0

你有什麼試圖調試它?你確認文件存在,你的路徑是否正確,文件是否被成功讀取,$ filenameArray在返回等之前是否有正確的值? – FluffyKitten

+0

文件夾中存在文件。 Wordpress沒有在上面的代碼中記錄任何錯誤。移動語句echo json_encode($ filenameArray);在while循環中返回包含圖像信息的數組。 – user1404963

+0

所以問題是數組得到清除不知何故,是嗎?在while循環中的位置是數組打印 - 它是否在'if($ width!== null && $ height!== null)之前或之後「 '? – FluffyKitten

回答

0

到json_encode()的調用失敗。你應該檢查對json_encode調用的錯誤。

$json = json_encode($filenameArray); 
if ($json !== FALSE) { 
    echo $json; 
} else { 
    error_log('json_encode() failed with error=' . json_last_error()); 
} 

有可能是json_encode()無法處理的另一個條目。您應該跳過此條目或將選項設置爲json_encode()以處理條目中的字符。

+0

非常感謝。這解決了我的問題。我真的很感激。 – user1404963

+0

我第一次遇到這個問題需要很長時間才能解決 - 缺點是PHP手冊中的示例頁面沒有顯示錯誤檢查。 – B68C

+0

這讓我非常震驚。我從昨天開始一直在尋找它。對於您的寶貴回覆,我們無法表達您的謝意。 – user1404963