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