我希望能够从数据库中提取单个记录,将该记录存储到一个数组中,然后显示该数组中的随机值,并且该随机值不能是0索引位置,因为这是记录的ID字段。
我有两张表。一个是questions
,另一个是answers
。Questions
有两个字段,ID
和Question
。Answers
有10个字段:ID, ANS1, ANS2, ANS3, etc.
因此,Answers
通过它们的ID
与Questions
相关联。
获取记录,我使用如下:
$json = array( );
mysql_select_db($database_localhost, $localhost);
$query_getSentence = "SELECT * FROM answers WHERE ID = 13";
$getSentence = mysql_query($query_getSentence, $localhost) or die(mysql_error());
while ( $row_getSentence = mysql_fetch_assoc($getSentence)) {
$json[] = $row_getSentence;
$totalRows_getSentence = mysql_num_rows($getSentence);
所以,当我使用print_r($json)
时,我得到这个:
Array (
[0] => Array (
[ID] => 13
[ANS1] => ducks
[ANS2] => chickens
[ANS3] => birds
[ANS4] => cats
[ANS5] => dogs
[ANS6] => elephants
[ANS7] => monkeys
[ANS8] => animals
[ANS9] => bees
)
)
现在,如果我理解正确的话,我认为你从数组中得到一个随机结果:
echo $myArray[array_rand($myArray)];
但是如果我把$json
放在我刚刚写的$myArray
的地方,它就不起作用了。我知道我必须使用json_encode
,但无论我尝试在上面的代码中插入多少不同的方法,它仍然不做任何事情。
另外,为了跳过第一个索引(ID字段),我尝试的方法是这样做:
echo(array_slice($myArray,1,9));
返回所有的答案并省略ID。但是,再一次,我不知道如何将所有这些东西组合成一段有效的代码。我怎么把这些都用在一起,让它正常工作?
如何使用shuffle
并像这样抓取数组的第一项:
shuffle($myArray)
echo $myArray[0];
但老实说,你的代码令人困惑。那么,如果这样做,$json
数组(不是json)的输出是什么?
echo '<pre>';
print_r($json);
echo '</pre>';
EDIT:随着原始海报更新的问题,似乎数组嵌套在另一个基于结构的数组中:
Array (
[0] => Array (
[ID] => 13
[ANS1] => ducks
[ANS2] => chickens
[ANS3] => birds
[ANS4] => cats
[ANS5] => dogs
[ANS6] => elephants
[ANS7] => monkeys
[ANS8] => animals
[ANS9] => bees
)
)
知道你会这么做。我假设$json
在这种情况下是数组:
$new_array = array_slice($json[0],1,9);
$random_key = array_rand($new_array);
$final_value = $new_array[$key];
所以array_slice
从$json[0]
中抓取项目1-9并将其分配给$new_array
。然后我们使用array_rand()
从$new_array
获得一个随机的键值。现在最后的值被设置为$final_value
和$new_array[$key]
。
我在这里使用array_rand
而不是我以前使用的shuffle
,因为很明显你想保留键