Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify a nested array into a single level array [duplicate]

Tags:

php

Possible Duplicate:
How to Flatten a Multidimensional Array?

Let's say I have an array like this:

array (
  1 => 
  array (
    2 => 
    array (
      16 => 
      array (
        18 => 
        array (
        ),
      ),
      17 => 
      array (
      ),
    ),
  ),
  14 => 
  array (
    15 => 
    array (
    ),
  ),
)

How would I go about tranforming it into array like this?

array(1,2,16,18,17,14,15);
like image 937
Richard Knop Avatar asked Nov 19 '10 07:11

Richard Knop


2 Answers

Sorry for the closevote. Didnt pay proper attention about you wanting the keys. Solution below:

$iterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($arr),
    RecursiveIteratorIterator::SELF_FIRST);

$keys = array();

and then either

$keys = array();
foreach($iterator as $key => $val) {
    $keys[] = $key;
}

or with the iterator instance directly

$keys = array();
for($iterator->rewind(); $iterator->valid(); $iterator->next()) {
    $keys[] = $iterator->key();
}

or more complicated than necessary

iterator_apply($iterator, function(Iterator $iterator) use (&$keys) {
    $keys[] = $iterator->key();
    return TRUE;
}, array($iterator));

gives

Array
(
    [0] => 1
    [1] => 2
    [2] => 16
    [3] => 18
    [4] => 17
    [5] => 14
    [6] => 15
)
like image 190
Gordon Avatar answered Sep 25 '22 06:09

Gordon


how about some recursion

$result = array();
function walkthrough($arr){ 
    $keys = array_keys($arr);
    array_push($result, $keys);
    foreach ($keys as $key)
    {
        if (is_array($arr[$key]))
           walkthrough($arr[$key]);
        else
           array_push($result,$arr[$key]);
    }
    return $result;
}
walkthrouth($your_arr);

P.S.:Code can be bugged, but you've got an idea :)

like image 28
Vadyus Avatar answered Sep 22 '22 06:09

Vadyus