0

I'm trying to link the MySQL while loop into foreach loop using something like this :

if($something == true){
  foreach($array as $arr){
} else {
  while($row = mysql_fetch_array($mysql_query)){
}
  // loop instructions
}

It looks so wrong, I know but you see what I am trying to do ?.. I want to grab data from array if $something was true, else then grab data from database

I had another solution idea and its to manually match the array with how $mysql_query works so I can use them both with while only, something like this :

if($something == true){
  $mysql_query = array("username" => "$_GET['username']", "password" => "$_GET['password']");
} else {
  $mysql_query = mysql_query("SELECT * FROM users WHERE usern......");
}

while($row = mysql_fetch_array($mysql_query)){
...

That's a second way to do it but it looks wrong as well because the first array is normal, I want to match that normal array with how mysql_query builds it so it can fit with the while loop

P.S. : I DO NOT want to repeat writing the loop instructions, I want them both to work with only one like I mentioned above

4

5 回答 5

2

将您的处理放入一个函数中:

function process_data($data) {
    // do stuff
}


if($something){
    foreach($array as $arr){
        process_data($arr);
    }
} else {
    while($row = mysql_fetch_array($mysql_query)){
        process_data($row);
    }
}
于 2012-12-26T14:09:20.820 回答
1

这里的其他答案很好,但是最好确保这$array是一个有效的数组,不管something......怎么样

if (!something){
    $array = array();
    while($row=mysql_fetch_array($mysql_query)) {$array[] = $row;}
}

foreach($array as $arr){
   // do work
}
于 2012-12-26T14:10:25.900 回答
0

如果您扩大了您所解释的范围,您可能会得到更好的答案。如果不知道某物是什么、数据是什么,再加上最终目标,那么很难判断您应该使用哪种结构。

在我看来,如果循环内的代码相同,您只需使用一个函数就可以实现这一点。像这样:

if($something == true)
{
    foreach($array as $arr)
    {
        doWork($arr);
    }
}
else
{
     while($row = mysql_fetch_array($mysql_query))
     {
         doWork($row);
     }
}

function doWork($arr)
{
 //...
}
于 2012-12-26T14:12:15.143 回答
-1

您不能在这样的循环内嵌套循环指令。您需要在 IF 语句中完全有两个单独的循环。

if($something == true){
  foreach($array as $arr){
     // do work
  }
} else {
  while($row = mysql_fetch_array($mysql_query)){
    // do work
  }
}
于 2012-12-26T14:07:17.513 回答
-1

也许你可以从这个角度来看。请注意,此代码使用 mysql_fetch_assoc() 而不是 mysql_fetch_array()。尝试这两个函数并使用 var_dump() 查看结果行。您将看到 mysql_fetch_array() 的数据量是原来的两倍。你可能想要那个,但可能不是。

if ($something !== true)
{
    $array = array();
    while($row = mysql_fetch_assoc($mysql_query_result_resource))
    {
        $array[] = $row;
    }
}
foreach($array as $arr)
{
    /* PROCESS */
}
于 2012-12-26T14:17:30.047 回答