2013-01-20 3 views
3

아래의 코드를 사용하는 은 GLOB_BRACE에 나열된 3 개의 폴더 중 임의의 파일에서 10 개의 임의 파일을 가져옵니다.글로브를 사용하는 PHP 에코 폴더 이름

예를 들면 :

$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); 

나는 그것이 그것을 읽어 내 페이지에 표시되는 경우

$thelist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>'; 

그래서 $의 thelist 아래에 보이는 URL에 폴더 이름을 반향하고 싶습니다. 사용

<p><a href="../folder1/page-name.php">what ever</a></p> 
<p><a href="../folder3/page-name.php">what ever</a></p> 
<p><a href="../folder1/page-name.php">what ever</a></p> 
<p><a href="../folder2/page-name.php">what ever</a></p> 
<p><a href="../folder1/page-name.php">what ever</a></p> 
<p><a href="../folder3/page-name.php">what ever</a></p> 
<p><a href="../folder2/page-name.php">what ever</a></p> 
<p><a href="../folder3/page-name.php">what ever</a></p> 
<p><a href="../folder1/page-name.php">what ever</a></p> 
<p><a href="../folder2/page-name.php">what ever</a></p> 

코드 :

<?php 
$files = (glob('../{folder1,folder2,folder3}/*.php', GLOB_BRACE)); /* change php to the file you require either html php jpg png. */ 
shuffle($files); 
$selection = array_slice($files, 0, 11); 

foreach ($selection as $file) { 
    $file = basename($file); 
    if ($file == 'index.php') continue; 

    $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME)); 
     $randomlist .= '<p><a href="../'.$folder 1 or 2 or 3.'/'.$file.'">'.$title.'</a></p>'; 
    } 
?> 
<?=$randomlist?> 
+0

무엇이 작동하지 않습니까? 폴더 이름을 가져 오는 데 문제가 있습니까? 'dirname ($ file)' –

+0

예 폴더 이름을 얻는 방법을 모릅니다. –

+0

'dirname ($ file)'이 당신을 얻는 것이어야합니다. –

답변

1

glob()는 디렉토리와 파일 이름을 반환합니다. 따라서 $filebasename($file)에 재 할당하지 않으면 전체 문자열이 그대로 출력됩니다. if()basename()continue으로 계속 확인할 수 있습니다.

foreach ($selection as $file) { 
    // Call basename() in the if condition, but don't reassign the variable $file 
    if (basename($file) == 'index.php') continue; 

    $title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME)); 
    // Using the full `$file` in the HTML output. No need for basename() or dirname(). 
    // Using htmlentities to encode the file path for an HTML attribute 
    $randomlist .= '<p><a href="' . htmlentities($file, ENT_QUOTES) . '">'.$title.'</a></p>'; 
} 
+0

대단히 감사합니다. –