Yesterday just contacted PHP, want to make a demand: through a PHP code, you can randomly generate a random number of values, inserted into the database, the structure is as follows:
Table Name: Test
Field name: User ID Aihao
Value: 1 Eat
Value: 20 Eat, sleep
Value: 35 Eat, sleep, hit peas
Value: 203 Sleep, hit the peas
Where the user ID is already present without modification. The value of a hobby needs to be given randomly. The code I wrote was this:
for ($i =0; $i <4; $i + +) {$aihao =array ("Eat", "Sleep", "hit the Peas"), $rn =rand (1,3); $result =array_rand ($aihao, Count ($rn)); $sql = "Replace into Test (Aihao) VALUES ($result)"; $re =mysql_query ($sql);}
The result is a fixed 1-digit number, not a random number of element names in the array, please help to see where the specific problem is.
Because the contact PHP is less than 2 days, the above code is Baidu out, I think the problem may be in the Array_rand function understanding of the above, according to the content of PHP help document, really do not see how to change, I hope you can point pointing, thank you.
Reply to discussion (solution)
Array_rand () returns the key name of the random element in the array
Change it to the following:
$result =array_rand ($aihao, Count ($rn)), $result = $aihao [Array_rand ($aihao, Count ($rn))];
1. $aihao Since this variable is not modified, it should be defined outside the loop
2. Check the manual, Array_rand returns a random key instead of a value, you define $aihao no key, that is 0,1,2
3. $rn just want a random number, why add count?
4. $result is an array in the case of multiple values and cannot be written directly to the SQL statement
';}
The Array_rand () function randomly selects one or more elements from the array, and if more than one element is selected, returns an array containing the random key names, otherwise returns the key name of the element.
Brother, sorry, has been in accordance with the results of the 2 floor of the Great God test success, to him, thank you for your earnest reply, sorry to occupy your time for me to solve the problem, thank you very much! I'm sorry.
It should be a bit better to change Rand's parameters to an array length.