简体   繁体   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 ) ) )

I have an array like this above, but when i use in_array like below to check the subject value, it will display negative result. 我上面有一个这样的数组,但是当我使用下面的in_array来检查主题值时,它将显示负结果。

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

haystack Should be an array haystack应该是一个数组

Please check the documentation for in_array 请检查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.

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

You are passing a wrong key so you are not getting desired output. 您传递了错误的密钥,因此无法获得所需的输出。

it should be 它应该是

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

or 要么

in_array("Computer", $cart_info)

or even 甚至

 if($item2 == "Computer")

instead of 代替

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

try 尝试

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

Because $item2['subject'] is not an array. 因为$item2['subject']不是数组。 In your case use: 在您的情况下使用:

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