Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]

It's probably beginner question but I'm going through documentation for longer time already and I can't find any solution. I thought I could use implode for each dimension and then put those strings back together with str_split to make new simple array. However I never know if the join pattern isn't also in values and so after doing str_split my original values could break.

Is there something like combine($array1, $array2) for arrays inside of multi-dimensional array?

like image 993
Adriana Avatar asked Feb 08 '09 22:02

Adriana


People also ask

How do I flatten a multidimensional array in PHP?

– Usage of Implementation of Method 2 $flattened = new RecursiveArrayIterator ($array); $flattened = new RecursiveIteratorIterator ($flattened); $flattened = iterator_to_array ($flattened, FALSE); var_dump ($flattened);


1 Answers

$array  = your array  $result = call_user_func_array('array_merge', $array);  echo "<pre>"; print_r($result); 

REF: http://php.net/manual/en/function.call-user-func-array.php

Here is another solution (works with multi-dimensional array) :

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); 
like image 127
Prasanth Bendra Avatar answered Oct 18 '22 15:10

Prasanth Bendra