2013-07-10 45 views
2

您好我有一個MySQL列表,每列下面有14列和1到10個行之間的行。我希望從每列中隨機調用一個條目來隨機組合條目。鑑於一個列可能只有一個條目在其下面,那麼每次都會調用該條目...如果它只有2個條目,那麼它會調用2中的1個,如果它有10個,那麼它會調用10箇中的1個等等都是隨機的!隨機句子使用PHP和MySQL

我用這個suggestion通過Matthew McGovern和它的作品很好,但它僅調用跨列的幾個條目,並從每個14

不是一個我可以修改代碼,使其調用一個從每個?

他的代碼:

<?php 
// Connect to database server 
mysql_connect("localhost", "xxx", "yyy") or die (mysql_error()); 
// Select database 
mysql_select_db("zzz") or die(mysql_error()); 
// SQL query 
$strSQL = "SELECT * FROM Users"; 
// Execute the query (the recordset $rs contains the result) 
$rs = mysql_query($strSQL); 
// Array to hold all data 
$rows = array(); 
// Loop the recordset $rs 
// Each row will be made into an array ($row) using mysql_fetch_array 
while($row = mysql_fetch_array($rs)) { 
    // add row to array. 
    $rows[] = $row; 
} 
// Close the database connection 
mysql_close(); 

// Max rand number 
$max = count($rows) - 1; 

// print out random combination of data. 
echo $rows[rand(0, $max)][0] . " " . $rows[rand(0, $max)][3] . " " 
    . $rows[rand(0, $max)][2] . " " . $rows[rand(0, $max)][3] . " " 
    . $rows[rand(0, $max)][4] . " " . $rows[rand(0, $max)][5]; 

?> 
+0

['array_rand()'](http://php.net/array-rand)更好。 – BlitZ

+0

而不是'$ rows = array();'?兩種方法都是一樣的嗎? – Joe

+1

*強制性的:*'mysql_ *'函數將[在PHP 5.5中棄用](http://php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated)。不建議編寫新代碼,因爲它將來會被刪除。取而代之的是,無論是[庫MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/en/book.pdo.php)和[是一個更好的PHP開發人員](http://jason.pureconcepts.net/2012/08/better-php-developer/)。 –

回答

1

我已經簡化下面的問題。你想要的是創建一個這樣的陣列結構來收集行:

[[col1row1, col1row2], [col2row1, col2row2], ...] 

每一列將基本上是一個行數組。比方說,這些都是你行:

$result = []; 
$row1 = [1, 2, 3]; 
$row2 = [4, 5, 6]; 

下面是執行的每一行與$result合併的一個小功能:

function colmerge(&$arr, $row) 
{ 
    foreach ($row as $key => $val) { 
     if (!isset($arr[$key])) { 
      $arr[$key] = []; 
     } 
     array_push($arr[$key], $val); 
    } 
} 

colmerge($init, $row1); 
colmerge($init, $row2); 

現在,$result內容是:

[[1, 4], [2, 5], [3, 6]] 

要隨機選擇每一列,只需執行以下操作:

print_r(array_map(function($item) { 
    return $item[array_rand($item)]; 
}, $init));