简体   繁体   English

如何在 while 循环中使用多个 list()/each() 调用?

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

I'm working with 3 different arrays (although I'm only testing with two for the time being) and I'm trying to process the arrays on $_POST .我正在使用 3 个不同的 arrays (尽管我暂时只测试两个)并且我正在尝试处理$_POST上的 arrays 。 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.如果我在任一数组上使用一个list() ,它将打印该特定项目的信息。 However, if I attempt to use multiple list() commands in the while, only the last list() ed item gets filled properly.但是,如果我尝试同时使用多个list()命令,则只有最后一个list() ed 项目被正确填充。 Is list() doing some trickery in the background that's preventing it from working in a while loop? list()是否在后台做了一些诡计,阻止它在 while 循环中工作?

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() ?我做错了什么,和/或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:您可以使用 array_keys() 提取每个数组的键,这会产生一个索引数组,然后为每个数组保留单独的循环计数器:

$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. &&以短路方式求值,第一个返回 false 的语句会跳出它。 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. list在这里应该可以正常工作,因为它是一种分配变量的语言结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM