2013-08-05 33 views
0

我這裏有我的php代碼和txt文件。我想在php的輸出中隨機顯示6行.txt文件。我該怎麼做。我嘗試我的代碼,但它只顯示前6行。 謝謝!PHP顯示前6行txt文件

PHP的:

require_once "config.php"; 
$txt_file = file_get_contents($database); 
$rows  = explode("\n", $txt_file); 
array_shift($rows); 
$i = 0; 
foreach($rows as $row => $data) 
{ 
    $row_data = explode('&id=', $data); 
    $info[$row]['name'] = $row_data[0]; 
    $info[$row]['id']  = $row_data[1]; 

    $name = $info[$row]['name']; 
    $id = $info[$row]['id']; 
    echo $name."<BR>"; 
    echo $id."<BR><BR>"; 

    if (++$i == "6") break; 
} 

txt文件:

ABC&id=1 
DEF&id=2 
GHI&id=3 
+0

嘗試洗牌數組,然後運行循環? http://php.net/manual/en/function.shuffle.php – Salman

回答

0
<? 
// read file content into array 
// http://fi2.php.net/file 
    $txt_file = file($database); 

// pick six elements randomly 
// http://fi2.php.net/array_rand  

foreach(array_rand($txt_file, count($txt_file)>6 ? 6 : count($txt_file)) as $row => $data) 
{ 
    $row_data = explode('&id=', $data); 
    $info[$row]['name'] = $row_data[0]; 
    $info[$row]['id']  = $row_data[1]; 

    $name = $info[$row]['name']; 
    $id = $info[$row]['id']; 
    echo $name."<BR>"; 
    echo $id."<BR><BR>"; 

} 
?> 
+0

警告:array_rand()[function.array-rand]:第二個參數必須介於1和數組中元素的個數 – user2651946

+0

所以你文件中沒有六行?我編輯了我的答案 – iiro