Loop an array of array

后端 未结 5 1503
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 07:36

in PHP, how can i loop an array of array without know if is or not an array?

Better with an example:

Array
(
    [0] => Array
        (
                   


        
相关标签:
5条回答
  • 2020-12-12 07:58

    Which approach to choose depends on what you want to do with the data.

    array_walk_recursive [docs] lets you traverse an array of arrays recursively.

    0 讨论(0)
  • 2020-12-12 08:07
    foreach( $array as $value ) {
        if( is_array( $value ) ) {
            foreach( $value as $innerValue ) {
                // do something
            }
        }
    }
    

    That would work if you know it will be a maximum of 2 levels of nested array. If you don't know how many levels of nesting then you will need to use recursion. Or you can use a function such as array_walk_recursive

    0 讨论(0)
  • 2020-12-12 08:12
    $big_array = array(...);
    function loopy($array)
    {
        foreach($array as $element)
        {
            if(is_array($element))
            {
                // Keep looping -- IS AN ARRAY--
                loopy($element);
            }
            else
            {
                // Do something for this element --NOT AN ARRAY--
            }
        }
    }
    
    loopy();
    
    0 讨论(0)
  • 2020-12-12 08:19

    You can use is_array to check if that element is an array, if it is, loop over it recursively.

    0 讨论(0)
  • 2020-12-12 08:24

    You can use is_array to check if something is an array, and/or you can use is_object to check if it can be used within foreach:

    foreach ($arr as $val)
    {
        if (is_array($val) || is_object($val)) 
        {
            foreach ($val as $subval)
            {
                echo $subval;
            }
        }
        else
        {
            echo $val;
        }
    }
    

    Another alternative is to use a RecursiveIteratorIterator:

    $it = new RecursiveIteratorIterator(
               new RecursiveArrayIterator($arr),
               RecursiveIteratorIterator::SELF_FIRST);
    
    foreach($it as $value)
    {
       # ... (each value)
    }
    

    The recursive iterator works for multiple levels in depth.

    0 讨论(0)
提交回复
热议问题