-3

I have a multidimensional array like below

Array
(
    [0] => Array
          (
            [0] => manoj
            [1] => karthi
          )
   [1] => Array
          (
            [0] => kumar
          )
)

I want to merge two array like this

Array
(
   [0] => manoj
   [1] => karthi
   [2] => kumar
)
Ivar
  • 6,138
  • 12
  • 49
  • 61
Manoj
  • 11
  • 1

2 Answers2

1

Use array_walk_recursive.

$return = [];

$array = [
    0 => [
        'manoj',
        'karthi',
    ],
    1 => [
        'kumar',
    ]
];

array_walk_recursive($array, function ($value, $key) use (&$return) {
    $return[] = $value;
});

var_dump($return);

Output

array (size=3)
  0 => string 'manoj' (length=5)
  1 => string 'karthi' (length=6)
  2 => string 'kumar' (length=5)

This will work for an array of any depth. It will NOT preserve the keys tho. So careful with that.

Also this requires annonymous functions so PHP >= 5.3.0 is required.

Andrei
  • 3,434
  • 5
  • 21
  • 44
0

You could use this, comes directly from Illuminate's Collection helpers :

function flatten($array, $depth = INF)
{
    return array_reduce($array, function ($result, $item) use ($depth) {    
        if (! is_array($item)) {
            return array_merge($result, [$item]);
        } elseif ($depth === 1) {
            return array_merge($result, array_values($item));
        } else {
            return array_merge($result, flatten($item, $depth - 1));
        }
    }, []);
}
Steve Chamaillard
  • 2,289
  • 17
  • 32