Search a multidimensional array php [duplicate]

2020-05-08 06:33发布

问题:

This question already has answers here:
Closed 8 years ago.

Possible Duplicate:
php. walk up multidimensional array?

I have a multidimensional arrray which contains arrays and objects. I have to search one value in it. How can I do?

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
                    (

Like this the array continue. How can I search if one value exists?

回答1:

If you only want to find out if a certain value exists and nothing else, this is trivial using recursive iterators:

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

It's not much more complex to write this up in a recursive function:

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;
}