2015-05-01 70 views
0

内的一个选择我有这些阵列:2 for循环嵌套,并根据外

$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other); 
$selected = array(2,1); 

foreach($payments as $key=>$value) { 
    foreach($selected as $id) { 
     if ($key == $id) { 
     echo $id . "is selected" . '<br>'; 
     } 
     else{ 
      echo $id . " is not selected" . '<br>'; 
     } 
    } 
} 

what expected: 
1 is selected 
2 is not selected 
3 is not selected 
4 is selected 

but i got: 
1 is not selected 
1 is selected 
2 is selected 
2 is not selected 
3 is not selected 
3 is not selected 
4 is not selected 
4 is not selected 

有什么错在我的循环?

+3

笑,4个内几乎相同的答案一分钟。 –

+1

为什么你期待这些结果呢?这与您选择的$数组不一致,这意味着只有2和1被选中。 –

+0

:) >>>>>>>>>> .. –

回答

1

你可以简单地使用in_array()检查是否选择的元素:

$payments = array(1=>'Cash',2=>'Cheque',3=>'credit',4=>'other'); 
$selected = array(2,1); 

foreach($payments as $key=>$value) { 
    if (in_array($key, $selected)) { 
     echo $value . "is selected" . '<br>'; 
    } else { 
     echo $value . " is not selected" . '<br>'; 
    } 
} 

顺便说一句,你需要周围的付款方式报价名。

5

你不需要内环:

$payments = array(1=>'Cash',2=>Cheque,3=>credit,4=>other); 
$selected = array(2,1); 

foreach($payments as $key=>$value) { 
    if (in_array($key, $selected)({ 
    echo $key . "is selected" . '<br>'; 
    } else { 
     echo $key . " is not selected" . '<br>'; 
    } 
} 
1

您可以使用in_array()代替,这样你就可以忽略你的内部循环:

foreach($payments as $key=>$value) { 
    if (in_array($key, $selected)) { 
    echo $id . "is selected" . '<br>'; 
    }else{ 
     echo $id . " is not selected" . '<br>'; 
    } 
} 

Example

0

UPDATE:的替代解决方案。没有更好的(也许),但不同的:)

$payments = array(1=>'Cash', 2=>'Cheque', 3=>'Credit', 4=>'Other'); 
$selected = array('Cash','Cheque'); 

foreach($selected as $chosen){ 
    $selected_values = array_search($chosen, $payments); 
    echo "Number ". $selected_values." (".$chosen.") is selected.<br>"; 
} 

You can see the output here


(如在其他人......)

$payments = array(1=>'Cash', 2=>'Cheque',3=>'Credit',4=>'Other'); 

    $selected = array(2,1); 

    foreach($payments as $key=>$value) { 
     if (in_array($key, $selected)) { 
     echo $key. " is selected" . '<br>'; 
     }else{ 
      echo $key. " is not selected" . '<br>'; 
     } 
    } 
+1

对于OP:请让我知道这是你想要的,或者如果我可以用任何其他方式帮助你与阵列。祝你今天愉快。 – Per76