while循环的Array_rand()没有返回值?

时间:2022-03-20 16:43:45

I have an t1 mysql table.

我有一个t1 mysql表。

Below is data:

以下是数据:

+-------+-------------+
| ID    | type        |
+---------------------+
| 1     | a           |
| 2     | a           |
| 3     | b           |
| 4     | a           |
+---------------------+

And I want to array_rand by type a, like array_rand(1,2,4);

我想通过类型a来array_rand,比如array_rand(1,2,4);

I try my coding as below:

我尝试编码如下:

$qadfirst = DB::query("SELECT * FROM ".DB::table('t1')." WHERE type = 'a'");
while($radfirst = DB::fetch($qadfirst)){
    $arr = array($radfirst['id']);
    implode(",",$arr);
    $random_keys=array_rand($arr,1);
    echo $arr[$random_keys[0]]."<br>";
};

I use the $random_keys from w3school, but still not working, How to make the coding works? Thank you.

我使用w3school的$ random_keys,但仍然无法正常工作,如何使编码工作?谢谢。

1 个解决方案

#1


1  

This line $arr = array($radfirst['id']); replace the value of $arr every time it fetch an ID from the database inside the loop, which will result to an array with only one value assigned to it at the end of the loop.

这行$ arr = array($ radfirst ['id']);每次从循环内的数据库中获取ID时,都会替换$ arr的值,这将导致在循环结束时只为其分配一个值的数组。

$arr array(1) 
  integer 4

Do something like this

做这样的事情

<?php
  $i = 0;
  while($radfirst = DB::fetch($qadfirst)){
    $arr[$i++] = $radfirst['id'];
  }
  $random_keys = array_rand($arr, 1);
  echo $arr[$random_keys]."<br>";
?>

as you loop through ID fetch from the database, get the ID and assign it to $arr the type array and increment the index value with $i or whatever variable you chose.

当您从数据库中循环访问ID时,获取ID并将其分配给$ arr类型数组,并使用$ i或您选择的任何变量递增索引值。

Outside the loop, use array_rand($arr, 1) to get the random keys and assign to $random_keys and the value of random_keys use it as an index value for $arr. $arr[$random_keys].

在循环外部,使用array_rand($ arr,1)获取随机密钥并分配给$ random_keys,random_keys的值将其用作$ arr的索引值。 $常用3 [$ random_keys。

#1


1  

This line $arr = array($radfirst['id']); replace the value of $arr every time it fetch an ID from the database inside the loop, which will result to an array with only one value assigned to it at the end of the loop.

这行$ arr = array($ radfirst ['id']);每次从循环内的数据库中获取ID时,都会替换$ arr的值,这将导致在循环结束时只为其分配一个值的数组。

$arr array(1) 
  integer 4

Do something like this

做这样的事情

<?php
  $i = 0;
  while($radfirst = DB::fetch($qadfirst)){
    $arr[$i++] = $radfirst['id'];
  }
  $random_keys = array_rand($arr, 1);
  echo $arr[$random_keys]."<br>";
?>

as you loop through ID fetch from the database, get the ID and assign it to $arr the type array and increment the index value with $i or whatever variable you chose.

当您从数据库中循环访问ID时,获取ID并将其分配给$ arr类型数组,并使用$ i或您选择的任何变量递增索引值。

Outside the loop, use array_rand($arr, 1) to get the random keys and assign to $random_keys and the value of random_keys use it as an index value for $arr. $arr[$random_keys].

在循环外部,使用array_rand($ arr,1)获取随机密钥并分配给$ random_keys,random_keys的值将其用作$ arr的索引值。 $常用3 [$ random_keys。