2013-04-01 3 views
1

Я получаю ошибку на этой линии:PHP array_merge

$ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat)); 

Ошибка: array_merge() Аргумент # 2 не является массивом

Я не знаю, знаю, чтобы решить эту проблему.

спасибо.

function preg_ls($path=".", $rec=false, $pat="/.*/") { 
    // it's going to be used repeatedly, ensure we compile it for speed. 
    $pat=preg_replace("|(/.*/[^S]*)|s", "\\1S", $pat); 
    //echo($pat); 
    //Remove trailing slashes from path 
    while (substr($path,-1,1)=="/") $path=substr($path,0,-1); 
    //also, make sure that $path is a directory and repair any screwups 
    if (!is_dir($path)) $path=dirname($path); 
    //assert either truth or falsehoold of $rec, allow no scalars to mean truth 
    if ($rec!==true) $rec=false; 
    //get a directory handle 
    $d=dir($path); 
    //initialise the output array 
    $ret=Array(); 
    //loop, reading until there's no more to read 
    while (false!==($e=$d->read())) { 
     //Ignore parent- and self-links 
     if (($e==".")||($e=="..")) continue; 
     //If we're working recursively and it's a directory, grab and merge 
     if ($rec && is_dir($path."/".$e)) { 
      $ret=array_merge($ret,preg_ls($path."/".$e,$rec,$pat)); 
      continue; 
     } 
     //If it don't match, exclude it 
     if (!preg_match($pat,$e)) continue; 
     //In all other cases, add it to the output array 
     //echo($path."/".$e."<br/>"); 
     $ret[]=$path."/".$e; 
    } 
    //finally, return the array 
    echo json_encode($ret); 
} 
+0

Если 'preg_ls' возвращает строку json, вы не можете передать ее в' array_merge', потому что она ожидает массив. – Emissary

+0

... 'json_encode()' дает строку, а не массив. – Amelia

+0

return $ ret; вместо echo json_encode ($ ret) – Thorsten

ответ

6

Array в PHP не JSON. Это массив. Просто return $ret;

Вы должны вернуть массив, если вы ожидаете массив, а не строку (как указывает json_encode).

Кроме того, вы используете echo, а не return. echo печатает либо stdout, либо тело HTML, в зависимости от среды PHP (хотя они одно и то же, просто с переадресацией и другой средой для ее обработки).

return приведет к тому, что функция передаст свое возвращаемое значение вызывающему абоненту, как и ожидалось (обычно в переменную или другую функцию); без возвращаемого значения, функция всегда будет возвращать NULL.

Смежные вопросы