Jump to content

Getting a random number from an array and select that many from the array


marcus

Recommended Posts

[code]
$sql = "SELECT * FROM `list_items` WHERE `type` ='Food'";
$res = mysql_query($sql) or die(mysql_error());
$array = array();
while ($row = mysql_fetch_assoc($res)) {
  $array[] = $row['ID'];
}
foreach($array as $val) {
  $array = "$val,";
  echo $array;
}
[/code]

Is what I'm trying to do is to have an array ($array) probably explode it, and then do a random number 1,20 and then take the random number and select that many items from the array, and insert them into the database.
Something like?

[code]
<?php
  $sql = "SELECT * FROM `list_items` WHERE `type` ='Food'";
  $res = mysql_query($sql) or die(mysql_error());
  $array = array();
  $total = mysql_num_rows($res);
  while ($row = mysql_fetch_assoc($res)) {
    $array[] = $row['ID'];
  }
  $num = rand(1,$total);
  for ($i = 0;$i <= $num; $i++)
    if (mysql_query("INSERT INTO tbl (fld) VALUES ('{$array[$i]}');")) {
      echo $array[$i]." inserted";
    }
  }
?>
[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.