簡體   English   中英

PHP in_array()意外結果

[英]PHP in_array() unexpected result

這是$ feed_content數組

Array
    (
        [0] => Array
            (
                [id] => 1
                [link] => http://www.dust-off.com/10-tips-on-how-to-love-your-portable-screens-keeping-them-healthy
    )
        [1] => Array
            (
                [id] => 2
                [link] => http://www.dust-off.com/are-you-the-resident-germaphobe-in-your-office
            )
     )

----另一個陣列----------
這是$ arrFeeds數組

Array
(
    [0] => Array
        (
            [title] => 10 Tips on How to Love Your Portable Screens (Keeping them Healthy)
            [link] => http://www.dust-off.com/10-tips-on-how-to-love-your-portable-screens-keeping-them-healthy
  )
   [1] => Array
        (
            [title] => Are You the Resident Germaphobe in Your Office?
            [link] => http://www.dust-off.com/are-you-the-resident-germaphobe-in-your-office
        )


)

這是我的代碼:

foreach( $arrFeeds as $key2 => $value2 )
    {
        $feed_content = $feed->get_feed_content( $value['id'] );

        if( !in_array( $value2['link'], $feed_content ) )
        {
            echo "not match!";
        }
    }

題:
即使$ feed_content鏈接值具有$ arrFeeds鏈接的值,為什么代碼總是進入if語句? 我的預期結果應該是我的代碼會告訴我$ feed_content鏈接值是否不在$ arrFeeds中。 順便說一句, $feed_content代碼返回我在上面指定的數組。 這個應該是什么問題。 提前致謝! :)

這是因為你的數組元素$ feed_content也是關聯數組(帶有id和link鍵)

你正在檢查鏈接(一個字符串)是否等於數組中的任何元素(所有這些數組)

編輯:

要實現你想要的,你可以使用“黑客”。 您可以使用以下內容代替in_array:

$search_key = array_search(array('id'=>true,'link'=>$value2['link']), $feed_content);//use true for the id, as the comparison won't be strict
if (false !== $search_key)//stict comparison to be sure that key 0 is taken into account
{
    echo 'match here';
}

這個東西依賴於這樣一個事實,你可以使用數組作為array_search函數的搜索針,並且比較不會嚴格,所以true將匹配任何數字(0除外,但我想你不使用0作為id)

這種方式唯一真正重要的領域是鏈接

之后你需要使用嚴格的比較,以確保如果找到的鍵為0,你將使用它

in_array不會遞歸搜索。 它將$feed_content視為

Array
(
    [0] => Array
    [1] => Array
)

現在,您可以通過$feed_content將if子句擴展到foreach:

$found = false;
foreach($feed_content as $feedArr)
{
    if(in_array($value2['link'], $feedArr))
    {
        $found = true;
    }
}
if(!$found) echo "not match!";
if( !in_array( $value2['link'], $feed_content ) )



if( !in_array( $value2['link'], array_values($feed_content)) )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM