1

我有几行代码,但找不到正确使用它的正确方法。

$cc = 0;
$tt = 50;

while ($row = mysql_fetch_assoc($result)) {

//building array with values from DB.

    if (++$cc < $tt)
        continue;

    for ($i = 0; $i < $tt; $i++) {

    //Work with the array

    }
}

假设我在 DB 中有 133 个结果。它将获得前 50 个 - 在 for 循环中执行某些操作,然后再执行 50 个,将再次通过 for 循环并停止。最后 33 个结果将保持不变。它会得到它们,但因为无法达到 50 将停止并且它们不会通过 for 循环。

我的问题是如何在下面的循环中“发送”它们?

4

4 回答 4

2

在函数中移动 for 循环并在 while 循环之后调用它:

$cc = 0;
$tt = 50;
while ($row = mysql_fetch_assoc($result)) {

//building array with values from DB.

    if (++$cc < $tt) continue;

    work_with_array($array);
}
if($cc) work_with_array($array);

function work_with_array($array) {
    for ($i = 0; $i < count($array); $i++) {
        //Work with the array
    }
}
于 2011-11-22T12:38:56.403 回答
1

试试这个:

$i = 0
while ($row = mysql_fetch_assoc($result)):
  if($i < 50):
   //Code when $i is less than 50
   //Insert code here

  elseif($i > 50 && $i < 100):
   //Code when $i is more than 50 but less than 100
   //Insert code here

  elseif($i > 100):
   //Code when $i is more than 100
   //Insert code here

  endif;
 $i++;
endwhile;

所以所有的结果都经过这个循环。如果 $i 小于 50(或者如果结果小于 50)则执行一些代码,或者如果 $i 大于 50 但小于 100 则执行一些不同的代码。最后,如果 $i 大于 100,则执行一些其他代码。

你明白吗?

于 2011-11-22T11:55:06.967 回答
0

你可以试试:

$i = 0
while ($row = mysql_fetch_assoc($result) && $i < 100):
  if($i < 50):
   //Code when $i is less than 50
  else:
   //Code more than or equal to 50
  endif;
 $i++;

endwhile;
于 2011-11-22T11:02:46.357 回答
0

循环内的所有 continue 似乎都是不必要的。如果您只是尝试处理整个结果集并分块执行某些操作,则可以执行此操作

$cc = 0;
$tt = 50;
$result_array = array();

// this will chunk your array into blocks
while ($row = mysql_fetch_assoc($result)) {

    //building array with values from DB.
    $result_array[intval($cc++/$tt)] = $row;

}

// at this point you should have result_array with indexes:0,1,2 and have subarrays with 50, 50, 33 entries each.


foreach ($result_array as $k=>$sub_array) {
    //Work with your sub array
    foreach ($sub_array as $one_row)
    {
       // do something with the row
    }
}

我确实同意@Col.Shrapnel。为什么要在 while 循环中创建另一个数组,只是为了一次一行地遍历该数组来做某事?如果您一次发送一批数据(例如批量插入数据库,当然),那将是有道理的,但再次循环似乎很奇怪。为什么你不能在 while 循环中做同样的事情

于 2011-11-22T14:01:46.570 回答