Php 2个用于嵌套的循环,并基于外部循环在一个循环内选择
我有以下阵列:Php 2个用于嵌套的循环,并基于外部循环在一个循环内选择,php,arrays,Php,Arrays,我有以下阵列: $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>';
$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
我的循环有什么问题?您不需要内部循环:
$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>';
}
}
foreach($payments as $key=>$value) {
if (in_array($key, $selected)) {
echo $id . "is selected" . '<br>';
}else{
echo $id . " is not selected" . '<br>';
}
}
您可以简单地使用来检查是否选择了元素:
$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>';
}
}
顺便说一下,您需要在付款方式名称周围加引号。您可以使用引号,这样您就可以省略内部循环:
$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>';
}
}
foreach($payments as $key=>$value) {
if (in_array($key, $selected)) {
echo $id . "is selected" . '<br>';
}else{
echo $id . " is not selected" . '<br>';
}
}
更新:一种替代解决方案。也许不是更好,但不同:
$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>";
}
像其他人一样的老办法
$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>';
}
}
哈哈,一分钟内有4个几乎相同的答案。顺便问一下,你为什么期待这些结果?它与您的$selected数组不一致,这意味着只选择了2和1。我认为OP没有得到预期的答案谢谢各位,下面的所有答案都是正确的。遗忘在数组中:然后请用期望的答案更新问题,并接受其中一个答案。OP:请让我知道这是否是您想要的,或者我是否可以在数组中以任何其他方式帮助您。祝您有个美好的一天。