gpt4 book ai didi

php - 使用 PHP 和 MySQL 的随机句子

转载 作者:行者123 更新时间:2023-11-29 03:04:46 24 4
gpt4 key购买 nike

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

我用了这个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];

?>

最佳答案

我已经简化了下面的问题。你想要的是创建一个像这样的数组结构来收集行:

[[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));

关于php - 使用 PHP 和 MySQL 的随机句子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17561543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com