开发者

How do I use multiple list()/each() calls in a while loop?

I'm working with 3 different a开发者_Python百科rrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST. I'm currently using:

while(list($key_member,$member)=each($_POST['member_ids']) 
    && list($key_amount,$amount)=each($_POST['payment_amounts']))
{
    echo "MEMBER: $member<br>";
    echo "AMOUNT: $amount<br><br>";
}

If I use one list() on either array it will print the info for that particular item. However, if I attempt to use multiple list() commands in the while, only the last list()ed item gets filled properly. Is list() doing some trickery in the background that's preventing it from working in a while loop?

Obviously the "easy" solution would be to use an index and simply force the issue, but I prefer enumerating -- and I'm honestly just curious as to

What am I doing wrong, and/or what is "broken" with list()?


bug? dunno. here's a workaround.

while(list($key_member,$member)=each($_POST['member_ids'])){
   list($key_amount,$amount)=each($_POST['payment_amounts']);
   echo "MEMBER: $member<br>";
   echo "AMOUNT: $amount<br><br>";
}


You could extract each array's keys using array_keys(), which produces an indexed array, then keep separate loop counters for each array:

$member_ids = array_keys($_POST['member_ids']);
$amounts = array_keys($_POST['payment_amounts']);

$mi = 0;
$am = 0;
while(1) {
   ...

   $mi++
   $am++;
   if (count($member_ids) >= $mi) && (count(amounts) >= $am) {
      break;
   }
}


&& is evaluated in a short-circuit manner, the first statement to return false jumps out of it. In your case it stops to iterate as soon as the first array is at its end. list should work fine here, as it's a language construct which assigns variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜