6

i have array like this.........

Array
(
    [0] => Array
        (
            [0] => rose
            [1] => monkey
            [2] => donkey
        )

    [1] => Array
        (
            [0] => daisy
            [1] => monkey
            [2] => donkey
        )

    [2] => Array
        (
            [0] => orchid
            [1] => monkey
            [2] => donkey
        )

)

and i want like this.........

Array
(
    [0] => rose
    [1] => monkey
    [2] => donkey
    [3] => daisy
    [4] => monkey
    [5] => donkey
    [6] => orchid
    [7] => monkey
    [8] => donkey
)

....I used array merge but it's not working because my array generates dymaically and each time shows different arrays. problem is I can't pass arrays dynamically in array_merge() function.It accepts only manually entries of array and not accepts any other variable .function accepts only array.

it works like this ...

$total_data = array_merge($data[0],$data[1],$data[2]);

as each time it generates different numbers of array dynamically so i have to use like this....

$data_array = $data[0],$data[1],$data[2];

 $total_data = array_merge($data_array);

but it shows an error "array_merge() [function.array-merge]: Argument #1 is not an array"......

2
  • Why don't you use array_push to create a new array as your requirements. php.net/manual/en/function.array-push.php Commented Feb 19, 2013 at 7:17
  • array_push($output, ...$input); Commented Apr 8, 2021 at 2:45

2 Answers 2

23

Try this :

$array  = your array

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

echo "<pre>";
print_r($result);

Or try this :

function array_flatten($array) {

   $return = array();
   foreach ($array as $key => $value) {
       if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
       else {$return[$key] = $value;}
   }
   return $return;

}

$array  = Your array

$result = array_flatten($array);

echo "<pre>";
print_r($result);
Sign up to request clarification or add additional context in comments.

4 Comments

THIS is the correct answer to this question, had to go through 3 questions and bad answers to realize this, thanks.
Your first answer doesn't work with a multi-dimensional array. 3v4l.org/tY8vD
array_merge solution is a brilliant way to flatten 2 level array
but how about nesting level of a multidimensional array over 100, 200, 500 ??? dangerous code !
2

try this.....

       $result = array();
        foreach($data  as $dat)

          {
                foreach($dat as $d) 

                 {
                   $result[] = $d;

                 }

           }

1 Comment

foreach ($data as $arr) foreach ($arr as $val) $result[] = $val; Really no need for such complicated array iteration...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.