【问题标题】:Random Sentence Using PHP & MySQL使用 PHP 和 MySQL 的随机句子
【发布时间】:2013-07-10 02:28:26
【问题描述】:

您好,我有一个 MySQL 表,它有 14 列,每列下方的行中有 1 到 10 个条目。我希望从每一列中随机调用一个条目以随机组合条目。假设一列下面可能只有一个条目,那么每次都会调用该条目......如果它只有 2 个条目,那么它将调用 2 个条目中的 1 个,如果它有 10 个,那么它将调用 10 个条目中的 1 个等等都是随机的!

我通过Matthew McGovern 使用了这个suggestion,它工作得很好,但它只调用了跨列的几个条目,而不是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];

?>

【问题讨论】:

标签: php mysql random


【解决方案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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-29
    • 2017-02-11
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多