Reputation: 31
Hi I have a MySQL table with 14 columns and between 1 and 10 entries in rows beneath each column. I wish to randomly call one entry from each column to make a random combination of entries. Given that a column might only have one entry beneath it then that entry would then be called every time... if it had only 2 entries then it would call 1 of the 2, if it had 10 then it would call 1 of the 10 etc. all random!
I used this suggestion by Matthew McGovern and it works great but it only calls a few entries across the columns and not one from each of the 14.
Can I modify the code to make it call one from each?
His code:
<?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];
?>
Upvotes: 2
Views: 611
Reputation: 173562
I've simplified the problem below. What you want is to create an array structure like this to collect the rows:
[[col1row1, col1row2], [col2row1, col2row2], ...]
Each column will be an array of rows, basically. Let's say these are your rows:
$result = [];
$row1 = [1, 2, 3];
$row2 = [4, 5, 6];
Here's a small function that performs the merge of each row with $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);
Now, the contents of $result
is:
[[1, 4], [2, 5], [3, 6]]
To take a random row of each column, you simply do this:
print_r(array_map(function($item) {
return $item[array_rand($item)];
}, $init));
Upvotes: 1