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
  • 37,596
  • 11
  • 75
  • 105
Kanishka Panamaldeniya
  • 16,732
  • 29
  • 117
  • 190
  • 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
  • 184,866
  • 48
  • 414
  • 792
VolkerK
  • 93,904
  • 19
  • 160
  • 225
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,323
  • 6
  • 47
  • 68