2

How can I get the value of this array:

Array
(

    [0] => 20
    [1] => Array
        (
            [0] => 21
            [1] => 22
            [2] => Array
                (
                    [0] => 23
                    [1] => Array
                        (
                            [0] => 52
                            [1] => 
                        )

                )

        )

)

I want to get this values: 20, 21, 22, 23 and 52.

Thanks in advance! :)

rayss
  • 637
  • 2
  • 9
  • 19

2 Answers2

1

This code should do it:

function flatten_array($a)
{
    $retval = array();
    foreach ($a as $value)
    {
        if (is_array($value))
            $retval = array_merge($retval,flatten_array($value));
        else
            $retval []= $value;
    }
    return $retval;
}
AndreKR
  • 32,613
  • 18
  • 106
  • 168
0

I want to get this values: 20, 21, 22, 23 and 52.

Translated as getting an array of all values of an original array recursively. Using standard array_walk_recursive function...


$test_array = array(
    20,
    array(
        21,
        22,
        array(
            23,
            array(
                52,
                null
                )
            )
        )
    );

$array_extracted = array();

array_walk_recursive($test_array, function($val, $key) use (&$array_extracted) {if (!is_array($val)) $array_extracted[] = $val;});

print_r($array_extracted);
/*
gives: Array
(
    [0] => 20
    [1] => 21
    [2] => 22
    [3] => 23
    [4] => 52
    [5] =>
)
*/


bob-the-destroyer
  • 3,164
  • 2
  • 23
  • 30