Ch Hong
Ch Hong

Reputation: 3

Flatten a 3d array to a 2d array

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [win_number] => 2389
                    [id] => 1
                    [user_id] => 2
                )

            [1] => Array
                (
                    [win_number] => 2993
                    [id] => 2
                    [user_id] => 2
                )

            [2] => Array
                (
                    [win_number] => 9931
                    [id] => 3
                    [user_id] => 2
                )


        )

    [1] => Array
        (
            [0] => Array
                (
                    [win_number] => 3748
                    [id] => 14
                    [user_id] => 7
                )

            [1] => Array
                (
                    [win_number] => 9393
                    [id] => 15
                    [user_id] => 7
                )

            [2] => Array
                (
                    [win_number] => 3782
                    [id] => 16
                    [user_id] => 7
                )              

        )

)

Does anyone know how can convert this array into one array ya? For example, it will become array([0] = Array(..),[1] = Array(..) ,[2] = Array(..),[3] = = Array(..),[4] = Array(..),[5] = Array(..),[6]...). Please advice :((((. Thus, the first array need to use for loop because it will have many based on user add

Upvotes: 0

Views: 64

Answers (2)

Hermueller
Hermueller

Reputation: 195

Merging subarray into one array

If you are simply looking for a method to merge subarrays together:

// this is just testdata
$array1 = array(11, 12, 13, 14);
$array2 = array(21, 22, 23, 24);
$array3 = array(31, 32, 33, 34);
$array4 = array(41, 42, 43, 44);

$parentArray = array($array1, $array2, $array3, $array4);

// the array where all subArrays will be placed in
$result = array_merge(...$parentArray);


print_r($result);

But be aware that the array_merge method will overwrite values with the same key. So if an array is initialized as array("fruit" => "apple") and another with array("fruit" => "banana") the latter will overwrite the former.

But nothing is overwritten if the keys are the default ones or unique.

I hope this helps.

Upvotes: 1

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

If you are looking for to combine all the sub-arrays in a single array, just use ... splat operator with array_merge

$f = array_merge(...$a);

Working example :- https://3v4l.org/co1pc

Upvotes: 0

Related Questions