如何在php中使用in_array的子​​数组?

Per*_*ack 2 php arrays

我需要验证一个值是否在数组中,并且我正在使用php函数in_array().我发现当我发送给in_array()函数的数组由子数组组成时,它不起作用.无论如何都要对子阵列进行此验证吗?为了帮助您理解我的问题,我有以下代码:

$userIds = array();
foreach($accounts as $account){
    $accounIds[] = $account->getId();
    $userIds[] = AccountUserBeanHome::findAllIdsByAccountId($account->getId());
}
$userId = 225;
if (in_array($userId, $userIds, true)) {
    do action...
}
Run Code Online (Sandbox Code Playgroud)

问题是数组$ userIds可能是这样的:

Array
(
[0] => Array
    (
        [0] => 225
        [1] => 226
        [2] => 227
        [3] => 228
        [4] => 229
        [5] => 230
        [6] => 340
        [7] => 355
    )

[1] => Array
    (
        [0] => 313
        [1] => 314
        [2] => 315
        [3] => 316
        [4] => 318
        [5] => 319
    )

[2] => Array
    (
        [0] => 298
        [1] => 301
        [2] => 302
        [3] => 338
    )

)
Run Code Online (Sandbox Code Playgroud)

我注意到in_array()无法检查子数组,所以我希望你的帮助可以做这个验证...也许是一种让所有子数组元素成为主数组元素的方法......好吧..我希望你能帮我.

Mar*_*ijn 12

你需要的是一个递归的in_array.幸运的是,很多人已经做到了这一点.

这个直接来自PHP手册评论部分:http://www.php.net/manual/en/function.in-array.php#84602

<?php 
function in_array_recursive($needle, $haystack) { 
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($haystack)); 
    foreach($it AS $element) { 
        if($element == $needle) { 
            return true; 
        } 
    } 
    return false; 
} 
?>
Run Code Online (Sandbox Code Playgroud)