繁体   English   中英

PHP的foreach循环in_array不显示积极的结果

[英]php foreach loop in_array doesn't display positive result

Array ( [0] => Array ( [0] => Array ( [subject] => Computer [price] => 33.00 [quantity] => 1 ) ) )

我上面有一个这样的数组,但是当我使用下面的in_array来检查主题值时,它将显示负结果。

foreach ($cart_info as $item){
    foreach ($item as $item2){
        if (in_array("Computer", $item2['subject'])) {
        echo "Yes";
        }else{
            echo "No";
        }   
    }
}   

haystack应该是一个数组

请检查in_array的文档

bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )

 haystack

    The array.
strict

    If the third parameter strict is set to TRUE then the in_array() function will also check the types of the needle in the haystack.

参考: http : //in2.php.net/in_array

您传递了错误的密钥,因此无法获得所需的输出。

它应该是

in_array("Computer", $cart_info[0]) 

要么

in_array("Computer", $cart_info)

甚至

 if($item2 == "Computer")

代替

in_array("Computer", $item2['subject'])

尝试

if (in_array("Computer", $item2)) {
   echo "Yes";
}else{
   echo "No";
} 

因为$item2['subject']不是数组。 在您的情况下使用:

foreach ($cart_info as $item){
    foreach ($item as $item2){
        if ("Computer" == $item2['subject'])) {
        echo "Yes";
        }else{
            echo "No";
        }   
    }
}   

暂无
暂无

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

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