我需要验证一个值是否在数组中,我为此使用了 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()
无法检查子数组,所以我希望你能帮忙做这个验证......也许是一种让所有子数组元素成为的所有元素的方法主阵列......好吧..我希望你能帮助我。
最佳答案
您需要的是一个递归的 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;
}
?>
关于php - 如何在 php 中使用 in_array 作为子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11609283/