簡體   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