-1

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data i have some like this

but the coding only combines the last value in the first array, not all values

is it possible to make it like that? so that I can take arrays easily

3 Answers3

1

Use array_merge (doc) and ... (which break array to separate arrays):

function flatten($arr) {
    return array_merge(...$arr);
}

$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth

In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode

Live example: 3v4l

dWinder
  • 11,597
  • 3
  • 24
  • 39
  • @FutraPlayer updated the answer for double loop - if this helps you you may mark it as accepted – dWinder Apr 29 '19 at 06:46
1

I would make use of the unpacking operator ..., combined with array_merge:

$array['test2'] = array_merge(...array_merge(...$array['test2']));

In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).

Demo: https://3v4l.org/npnTi

Jeto
  • 14,596
  • 2
  • 32
  • 46
0

if you have a array then you can use the below code

if(!empty($array['test2'])){
    $newarray = array();

    foreach ($array['test2'] as $arrayRow) {
        $newarray = array_merge($newarray,$arrayRow);
    }

    $array['test2'] = $newarray;
}
Varun Malhotra
  • 1,202
  • 3
  • 15
  • 28