2012-08-26 2 views
3

배열에있는 폴더에서 파일을 얻는 것을 도우십시오. array에있는 모든 jpg 파일 이름을 images 폴더에서 가져 오려고합니다. 그 후 rand을 사용하면 CSS 배경을 임의로 변경할 수 있습니다.PHP 배열로 폴더에서 jpg 파일을 얻으십시오

arry의 폴더에있는 JPG 파일.

$images=array("image1.jpg", "image2.jpg"); 

는 배열을 얻을 수

$images = glob("images/*.jpg"); 
// may want to verify that the $images array has elements before echoing 
echo '<style>body{background:url('.$images[array_rand($images)].') no-repeat;'; 
+0

Sooo ... 뭐가 문제입니까? 당신이 시도한 바가 부적절한가? –

+0

배열의 폴더에서 파일을 가져 오는 방법을 모른다. –

+0

[Manual is your friend] (http://php.net/manual/en/function.readdir.php) - williamcomartin이 작성한 gmail dot com의 함수 찾기 – Peter

답변

4

scandir에 디렉토리를 통과

함께 편집 array_rand 해결이 이미지를 무작위로

echo '<style>body{background:url('.$images[array_rand($images)].')no-repeat;'; 
1

glob를로드 할 rand를 사용 영형 f 해당 디렉토리에있는 모든 파일. 아마도 array_filter을 사용하여 비 이미지를 파일 확장명으로 필터링 할 수 있습니다.

$files = scandir('/image/path'); 

    function images_only($file) 
    { 
     return preg_match('/\.(gif|jpg|png)$/i', $file); 
    } 

    $files = array_filter($files, 'images_only'); 

$ 파일 이제 이미지 경로에서 이미지 만 포함해야합니다.

+0

'backcground : url (0); '을 반환하지 않습니다. –

+0

경로가 맞습니까? 디버깅을 시도하여 올바르게 채워지는지 확인하십시오. –

+0

'array_rand()'는 임의의 ** 키 **만을 반환합니다. – salathe

관련 문제