-1

I need to convert array of index array to single dimension array.

$a=[];
$a[0]=[1,2,3];
$a[1]=[4,5,6];
$a[2]=[7,8,9];
$a[3]=[1,4,7];

I need to merge these arrays as single array. Is there any built in function available for this? The expected output is

 [1,2,3,4,5,6,7,8,9,1,4,7]

That output must be an single dimension index array

4 Answers4

0

You can simple use foreach like:

$a=[];
$a[0]=[1,2,3];
$a[1]=[4,5,6];
$a[2]=[7,8,9];
$a[3]=[1,4,7];

$b = [];
foreach($a as $array){
    foreach($array as $value){
        $b[] = $value;
    }
}
print_r($b);

Result:

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 1 [10] => 4 [11] => 7 )


Suggest from @catcon you can use array_merge like:

$new_array = array_merge(...$a)

Reference:

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
0

This is the correct solution refereed from How to Flatten a Multidimensional Array?

$a=[];
$a[0]=[1,2,3];
$a[1]=[4,5,6];
$a[2]=[7,8,9];
$a[3]=[1,4,7];
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($a));
$output=iterator_to_array($it, FALSE);
0
$result = array_merge(...$a);
print_r($result);

The easiest way

0

From this question link:

<?php
$a=[];
$a[0]=[1,2,3];
$a[1]=[4,5,6];
$a[2]=[7,8,9];
$a[3]=[1,4,7];

$result = [];
array_walk_recursive($a,function($val) use (&$result){ $result[] = $val; });
var_dump($result);

Demo

matteoruda
  • 131
  • 1
  • 4