使用in_array()的2个值的PHP搜索数组列

时间:2017-03-10 11:22:24

标签: php arrays

如何使用in_array()在同一记录中搜索2个值? 例如,我想搜索' AuthorNiceName'价值和' AuthorType'值。

以下代码不符合我的要求。它应该返回" EU TEST"但它返回" CP TEST"。

提前致谢。

 $authors = array(
        array(
            'AuthorName' => 'John Smith',
            'AuthorNiceName' => 'john-smith',
            'AuthorType' => 'CP'
        ),
        array(
            'AuthorName' => 'Joe Bloggs',
            'AuthorNiceName' => 'joe-bloggs',
            'AuthorType' => 'EU'
        ),
    );



    if (in_array('joe-bloggs', array_column($authors, 'AuthorNiceName')) && in_array('EU', array_column($authors, 'AuthorType'))) {
        $authorType = 'CP TEST';
    }
    else {
        $authorType = 'EU TEST';
    }

    echo $authorType;

更新:我的最新代码使用@ Philipp的建议,我稍微调整了一下。但是,如果有其他用户具有相同的“作者类型”,那么它无法正常工作。它返回"没有匹配"?

$authors = array( //TODO
    array(
        'AuthorName' => 'John Smith',
        'AuthorNiceName' => 'john-smith',
        'AuthorType' => 'CP'
    ),
    array(
        'AuthorName' => 'Joe Bloggs',
        'AuthorNiceName' => 'joe-bloggs',
        'AuthorType' => 'EU'
    ),
    array(
        'AuthorName' => 'Matt Bat',
        'AuthorNiceName' => 'matt-bat',
        'AuthorType' => 'EU'
    ),    
);

$name = 'joe-bloggs';
$type = 'EU';
foreach ($authors as $author) {
    if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'EU') {
        $authorType = 'EU Test';
    }
   elseif ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'CP') {
        $authorType = 'CP Test';
    }
    else {
        $authorType = 'no match';
    }

}

echo $authorType; //returns "not match". it should return "EU Test".

1 个答案:

答案 0 :(得分:0)

看来,你应该使用一个循环来实现你想要的东西

$name = 'joe-bloggs';
$type = 'EU';
foreach ($authors as $author) {
    if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == $type) {
        // do something
    }
}

如果结果来自同一列,则使用带有array_column的in_array会丢失信息。使用array_search,您还可以比较列的索引,但这似乎是一个糟糕的解决方案......

更新

更新的问题是,在设置正确的值后覆盖$authorType var。如果已设置值,则应检查并仅设置新值。

$name = 'joe-bloggs';
$authorType = false;
foreach ($authors as $author) {
    if ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'EU') {
        $authorType = 'EU Test';
    } elseif ($author['AuthorNiceName'] == $name && $author['AuthorType'] == 'CP') {
        $authorType = 'CP Test';
    }
}

if ($authorType === false) {
    echo 'no match';
} else {
    echo $authorType;
}