-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
  • 5,377
  • 12
  • 50
  • 56
Manoj
  • 11
  • 1
  • 2
    Cool. What have you tried? How did it fail to do what you want? Please read [ask]. – Chris Jan 30 '18 at 13:13
  • 6
    Possible duplicate of [Turning multidimensional array into one-dimensional array](https://stackoverflow.com/questions/8611313/turning-multidimensional-array-into-one-dimensional-array) – Vishnu Bhadoriya Jan 30 '18 at 13:14

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,208
  • 5
  • 19
  • 37
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,191
  • 14
  • 30