Simplifying an Array - PHP

3

I have a multidimensional array where the data is as follows:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Brasil
                    [1] => Franca
                    [2] => Italia
                    [3] => China
                )

        )

)

I would like a method / function that would simplify the array to only one level, regardless of the number of levels, so that the data looks like this:

Array
(
     [0] => Brasil
     [1] => Franca
     [2] => Italia
     [3] => China
)
    
asked by anonymous 04.07.2016 / 22:49

3 answers

4

You can use functions from the class RecursiveIteratorIterator , example:

$a = array(array(array("Brasil","Franca","Italia","China")));
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
$novo = array();
foreach($it as $v) {
  $novo[] = $v;
}
print_r($novo);

Ideone

    
04.07.2016 / 22:58
3

Do this:

$array = array(
    array(
        array(
            'Brasil',
            'França',
            'Italia',
            'China'
        ),
    ),
);

$new_array = array_reduce($array, 'array_merge', array());
$new_array = array_reduce($new_array, 'array_merge', array());

echo '<pre>', print_r($new_array), '</pre>';

Output:

Array
(
    [0] => Brasil
    [1] => França
    [2] => Italia
    [3] => China
)
1

Or simplifying a little more, just one line:

$new_array = call_user_func_array('array_merge', call_user_func_array('array_merge', $array));
    
04.07.2016 / 22:57
2

You can do this:

$foo = array(array(0 => 'Brasil', 1 => 'Franca', 2 => 'Italia'),
    array(0 => 'USA', 1 => 'Russia', 2 => 'China'));

var_dump(call_user_func_array('array_merge', $foo));

Output:

array (size=6)
  0 => string 'Brasil' (length=6)
  1 => string 'Franca' (length=6)
  2 => string 'Italia' (length=6)
  3 => string 'USA'    (length=3)
  4 => string 'Russia' (length=6)
  5 => string 'China'  (length=5)
    
04.07.2016 / 22:58