Bucle una matriz de matriz

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
        (
            [0] => big
            [1] => small
        )

    [1] => Array
        (
            [0] => big
            [1] => tiny
        )

    [2] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
        )
    [3] => row
    [4] => cols
    [5] => blablabla
    [6] => Array
        (
            [0] => asd
            [1] => qwe
        )
}

¿alguna idea? Gracias.

preguntado el 08 de noviembre de 11 a las 18:11

5 Respuestas

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.

respondido 08 nov., 11:22

Puedes usar is_array to check if that element is an array, if it is, loop over it recursively.

respondido 11 mar '12, 03:03

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

Otra alternativa es utilizar un 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.

respondido 08 nov., 11:22

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

respondido 08 nov., 11:22

$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();

respondido 08 nov., 11:22

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.