Simplifying an Array - PHP

Asked

Viewed 270 times

3

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

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

        )

)

I would like a method/function that simplifies the array to only one level, independent of the number of levels, so that the data stays like this:

Array
(
     [0] => Brasil
     [1] => Franca
     [2] => Italia
     [3] => China
)
  • If your array in this format always uses this https://ideone.com/WLw7ma

3 answers

4


You can use class functions 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

  • 1

    Great answer. Now just create a function. I need to study more Iterators, help a lot.

  • Just doing this would solve: $values = array_values($array[0][0]);

  • 1

    @Ivanferrer for this example yes, more if the array had one or more dimensions, no, it wants something that simplifies the dimension independent array.

3

Do so:

$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 a line:

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

2

You can do it like 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));

Exit:

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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.