2013-04-01 39 views
1

我有一個1000行這樣的數組,我想轉換成一個字符串,但只有50行。從數組中獲取指定的行數量

$thearray = Array 
     (
      [0] => row1 
      [1] => row2 
      [2] => row3 
      [3] => row4 
      [4] => row5 
      [5] => row6 
      ... 
      [999] => row1000 
     ) 

輸出應該是這樣的,我會用:

$string1 = implode(',', $thearray); 

但正如我說需要$string1有從陣列只有50行,如果有可能,讓他們隨機。我需要一些建議。 THX

回答

0

你可以試試這個,看到說明和代碼中的註釋http://3v4l.org/hjuv6的示範

// Lets create a dummy array 
$array = array(); 

for($i = 0; $i < 1000; $i++) { 
    $array[] = $i; 
} 

// Lets make a randomized temporary array 
$backUpArray = $array; 
$tempArray = array(); 

for($i = 0; $i < 50; $i++) { 

    // Select random Index 
    $randomIndex = rand(0 , count($backUpArray)); 
    // Copy it to the temp array 
    $tempArray[] = $backUpArray[$randomIndex]; 
    // Delete the row from our backup 
    unset($backUpArray[$randomIndex]); 
    // Reorganize the key indexes 
    $backUpArray = array_values($backUpArray); 
} 


$string1 = implode(",", $tempArray); 

var_dump($string1);