2

我需要验证一个值是否在数组中,并且我正在使用 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...
}

问题是数组 $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
    )

)

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

4

3 回答 3

12

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

This one is directly from the PHP manual comments section: 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; 
} 
?>
于 2012-07-23T08:59:39.540 回答
2
$iterator = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($userIds), 
                RecursiveIteratorIterator::SELF_FIRST);

foreach($iterator as $key => $val) {
    if($val == $userId) {
        // do something
    }
}

Documentation about recursiveiteratoriterator.

Kudo's to gordon

于 2012-07-23T09:01:04.577 回答
1

You can flatten $userIds array using array_merge():

$userIds[] = array();
foreach($accounts as $account){
    $accounIds[] = $account->getId();
    $userIds = array_merge($userIds, AccountUserBeanHome::findAllIdsByAccountId($account->getId()));
}

Then call in_array() to check your id.

于 2012-07-23T09:02:34.670 回答