1

I have a array multi level

$array = array("14529" => array("900" => array("87" => array() ) ) );

print_r(array_keys($array)); // result array("14529");

How to merge this array to single array

$array = array("14529", "900", "87");
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102

3 Answers3

3

Here is a function that does what you want. It is done recursively, so it doesn't matter how deep the array is.

function mergeArrayMultiKeyToSingleArray($array, $result=[])
{
    foreach($array as $key => $value) {
        $result[] = $key;
        if(is_array($value)) {
            $result = mergeArrayMultiKeyToSingleArray($value, $result);
        }
    }

    return $result;
}

// USAGE:
$array = array("14529" => array("900" => array("87" => array() ) ) );
$array = mergeArrayMultiKeyToSingleArray($array);
// $array is now ["14529", "900", "87"]
GregorMohorko
  • 2,739
  • 2
  • 22
  • 33
1

The solution using RecursiveIteratorIterator class:

$arr = ["14529" => ["900" => ["87" => [] ] ] ];
$keys = [];
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::SELF_FIRST) as $k => $v) {
    $keys[] = $k;
}

print_r($keys);

The output:

Array
(
    [0] => 14529
    [1] => 900
    [2] => 87
)
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
0

I did this using class

class ArrayStripper
{
    private $items = [];

    public function strip($arrayOrItem)
    {
        if(is_array($arrayOrItem))
        {
            foreach ($arrayOrItem as $item)
            {
                $this->strip($item);
            }
        }
        else
        {
            $this->items[] = $arrayOrItem;
        }
    }

    public function get()
    {
        return $this->items;
    }
}

$array = [1 , [2,3] , 4 , [[5 , 6 , 7] , [8 ,9] , 10]];
$stripper = new ArrayStripper();
$stripper->strip($array);
var_dump($stripper->get());
Ali Faris
  • 17,754
  • 10
  • 45
  • 70