2

I have an array like this:

Array
(
    [23] => 540,
    [25] => Array
        (
            [656] => Array(671 ,680),
            [345] => 400
        )
)

I want to get the values:

540, 671, 680, 400

The problem for me is, that this array is growing and I don't know how many levels deep it will be.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193
  • http://stackoverflow.com/questions/3899971/implode-and-explode-multi-dimensional-arrays related. and should give you your answer. – Platipuss Mar 26 '12 at 12:36

2 Answers2

3

You can use SPL's RecursiveArrayIterator and RecursiveIteratorIterator with its LEAVES_ONLY flag.

self-contained example:

<?php
$rai = new RecursiveArrayIterator(getData());
// $rii = new RecursiveIteratorIterator($rai, RecursiveIteratorIterator::LEAVES_ONLY) - but this is the default
$rii = new RecursiveIteratorIterator($rai);
foreach($rii as $n) {
    echo $n, "\n";
}

// test data source    
function getData() {
    return array(
        23 => 540,
            25 => array(
                656 => array(671,680),
                345 => 400
            )
    );
}

prints

540
671
680
400
hakre
  • 193,403
  • 52
  • 435
  • 836
VolkerK
  • 95,432
  • 20
  • 163
  • 226
1

here's the solution:

$array = array
(

    23 => 540,

    25 => array
        (
            656 => array(671,680),
            345 => 400
        )
);

var_dump($array);

$result = array();
function fn($item, $key){
    global $result;
    if (!is_array($item)){
        $result[] = $item;
    }
}

array_walk_recursive($array, 'fn');

var_dump($result);

and the result

array
  23 => int 540
  25 => 
    array
      656 => 
        array
          0 => int 671
          1 => int 680
      345 => int 400
array
  0 => int 540
  1 => int 671
  2 => int 680
  3 => int 400
k102
  • 7,861
  • 7
  • 49
  • 69