1

我已经尝试在之前提出的其他问题中寻找解决方案(一如既往),但我似乎无法解决这个问题。

看,我想从一个表中获取多个唯一 ID(以随机顺序)并将它们存储在一个数组中而不回显它们。然后我想在循环中使用该数组变量,以便我可以在每次传递时递增键,并将另一个变量设置为该数组变量。令人困惑?我认为看代码会更清楚。

问题是我似乎无法将查询到的值存储到数组中以供以后在代码中使用。我粘贴了代码的相关部分,并用注释 /* */ 标签指出了我的问题点。

任何帮助表示赞赏。

<?php

include ('parse_functions.php');

if ($fetch['use_rand']=='yes')

{ $loop = 5;    
$concept = $fetch['concept'];
$countRandom = "SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND()";
$askForRandom = mysql_query($countRandom) or die(mysql_error());
/* HERE I NEED TO STORE RANDOM KEYS (exID) INTO AN ARRAY */ }

else

{  if (!empty($fetch['ex5'])) { $loop = 5; }
 elseif (!empty($fetch['ex4'])) { $loop = 4; }
 elseif (!empty($fetch['ex3'])) { $loop = 3; }
 elseif (!empty($fetch['ex2'])) { $loop = 2; }
 elseif (!empty($fetch['ex1'])) { $loop = 1; }
 else { $loop = 0; }

    }

     if ($loop!==0)

      {

         echo '<div id="examples">' . "\n";
         echo '<table class="showExample" cellspacing="0" cellpadding="0" border="0" align="center">' . "\n";

         $turns = 1;

             do {

             if ($fetch['use_rand']=='no')

              { $exID = $fetch['ex'.$turns.'']; }

             else

              { $exID = /* THIS IS WHERE I WILL USE "RANDOM VARIABLE" */; }

             $askExamples = "SELECT * FROM examples WHERE exID='$exID'";
             $getExamples = mysql_query($askExamples) or die(mysql_error());
             $sortExamples = mysql_fetch_assoc($getExamples);

             echo '<tr>' . "\n";

// ...and so on
4

2 回答 2

0

为什么不从一开始就在一个查询中获取所有正确的信息,如下所示:

select 
    a.exID,
    examples.someField,
    examples.someOtherField
from 
    examples
        join
        (
            SELECT 
                exID 
            FROM 
                examples 
            WHERE 
                concept='$concept' 
            ORDER BY 
                RAND() 
            limit 5
        ) a
            on a.exID=examples.exID

然后,您只需将它们弹出到一个数组(或更好的对象)中,每次都将所有相关信息放在一行中。

于 2012-08-05T00:54:56.473 回答
0

如果您需要做的就是将信息存储在一个数组中,这里有一个简单的方法。

/* code 
to open
db here
*/

/* assuming you have a value for $concept */

$countRandom = "SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND()";
$askForRandom = mysql_query($countRandom) or die(mysql_error());

$Element = 0; //Array elements start at ZERO. So this is to intialise it.
while ($Fields = mysql_fetch_array($askforRandom)) //As long as there are records, get them.
    {
    //Records are retrieved one at a time. So store each one's exID in the array element
    $Data[$Element] = $Fields["exID"];
    //Soon after storing one, increment the value of the $Element variable so it is ready for the next one.
    $Element++
    }

/* now you have the data in the array. So you can do what you like with it. */

希望能帮助到你

注意:读取数组时,请确保设置条件以检查您的计数器是否小于 $Element。这是因为在读取最后一条记录后,$Element 加一。希望这很清楚。

于 2012-08-05T00:56:18.210 回答