搜索多维数组php

时间:2011-10-19 07:10:23

标签: php arrays multidimensional-array

  

可能重复:
  php. walk up multidimensional array?

我有一个包含数组和对象的多维arrray。我必须在其中搜索一个值。我该怎么办?

view Object
(
[db_table] => views_view
[base_table] => users
[args] => Array
    (
    )

[use_ajax] => 
[result] => Array
    (
    )

[pager] => Array
    (
        [use_pager] => 
        [items_per_page] => 10
        [element] => 0
        [offset] => 0
        [current_page] => 0
    )

[old_view] => Array
    (
        [0] => 
    )

[vid] => 1
[name] => userone
[description] => userone
[tag] => 
[view_php] => 
[is_cacheable] => 0
[display] => Array
    (
        [default] => views_display Object
            (
                [db_table] => views_display
                [vid] => 1
                [id] => default
                [display_title] => Defaults
                [display_plugin] => default
                [position] => 1
                [display_options] => Array
                    (

像这样阵列继续。如何搜索是否存在一个值?

1 个答案:

答案 0 :(得分:2)

如果你只是想知道某个值是否存在而没有别的,那么使用recursive iterators这是微不足道的:

$found = false;
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
    if ($value == 'theValueImLookingFor') {
        $found = true;
        break;
    }
}

在递归函数中编写它并不复杂:

function recursive_in_array($array, $needle) {
    foreach ($array as $value) {
        $isIterable = is_object($value) || is_array($value);
        if ($value == $needle || ($isIterable && recursive_in_array($value, $needle))) {
            return true;
        }
    }
    return false;
}