2

I have an associate array that looks something like this:

array
(
   'device_1' => array('a','b','c','d'),
   'device_2' => array('x','y','z')
)

How can I implode the array into a standard array like this:

array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'x', 5 => 'y', 6 => 'z')

Or more simply:

array('a','b','c','d','e','x','y','z')

Does anybody know what I should do?

hohner
  • 11,498
  • 8
  • 49
  • 84
  • possible duplicate of [How to Flatten a Multidimensional Array?](http://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) – deceze Oct 08 '11 at 12:55
  • Absolutely none of those solutions work. Each one only shows the final child array of the parent associative array. – hohner Oct 08 '11 at 13:33

3 Answers3

4

You can do this:

$result = call_user_func_array('array_merge', $array);

which will give you:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => d
    [4] => x
    [5] => y
    [6] => z
)

Demo

hakre
  • 193,403
  • 52
  • 435
  • 836
  • whoops worked so much with the SPL Library Iterators that I forgot to simple use call_user_func_array :D +1 for simple way – Talisin Oct 08 '11 at 13:38
  • It does, but you first need to apply this per each outer leafs once until there is only one level of outer leafs. This is already part of the answer when you look at the question which is a multi dimensional array. If you have exemplary data with some code to demonstrate what you want to ask about, you can also just create a new question (if that hasn't been even asked in that form before). If not even this answer: http://stackoverflow.com/a/7696976/367456 – hakre Sep 12 '14 at 16:23
1

With the function array_merge you can merge arrays.

Example from: http://www.php.net/manual/en/function.array-merge.php

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

output:

Array
(
    [color] => green
    [0] => 2
    [1] => 4
    [2] => a
    [3] => b
    [shape] => trapezoid
    [4] => 4
)
Thomas
  • 2,127
  • 1
  • 32
  • 45
0

Using an associative array:

$devices = array
(
   'device_1' => array('a','b','c','d'),
   'device_2' => array('x','y','z')
);

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($devices));
foreach( $iterator as $value ) {
    $output[] = $value;
}

print_r($output); 

for more information you can read the RecursiveIteratorIterator class

Talisin
  • 614
  • 1
  • 6
  • 17
  • I've already tried array_merge, but it only ends up listing the final array of the parent multidimensional array. – hohner Oct 08 '11 at 13:10
  • oh my bad, you have an associate array instead of two arrays. I will write you something – Talisin Oct 08 '11 at 13:25