user648198
user648198

Reputation: 2020

Flatten a multidimensional associative array by one level

I don't know how to write a nested for loop to convert into a key value array.

This is the array structure.

I need to flatten the second level data to become the first level (combining JobDescription and userdetail array together).

array(2) {
    ["jobDescription"]=> array(5) {
        ["funeralFor"]=> string(6) "Myself"
        ["serviceType"]=> string(1) "1"
        ["religionType"]=> string(1) "2"
        ["area"]=> string(4) "2154"
        ["customerComment"]=> string(6) "fdfddf"
    }
    ["userDetail"]=> array(6) {
        ["contactEmail"]=> string(16) "fdddf@fffgfg.com"
        ["contactFirstName"]=> string(6) "fddfdf"
        ["contactLastName"]=> string(6) "fddffd"
        ["contactPhoneNumber"]=> string(10) "0420988191"
        ["signup"]=> array(2) {
            ["id"]=> string(32) "8048f0f7106c336e1a8825d1d3bec902"
            ["input"]=> string(3) "k5m"
        }
        ["agreement"]=> string(1) "1"
    }
}

Upvotes: 0

Views: 139

Answers (5)

hakre
hakre

Reputation: 198117

The array_merge() function can create an array from multiple arrays. In your example, it works this way:

$yours = array(...);
$values = array_merge($yours["jobDescription"], $yours["userDetail"]);

Upvotes: 0

Brendan Bullen
Brendan Bullen

Reputation: 11819

You only need to loop once. No need for nesting. This solution covers where you have an undefined number of arrays to combine. Otherwise, you can use array_merge as suggested by Dickie

$allValues = array();

if(count($mainArray) > 0)
{
    foreach($mainArray as $arr)
    {
        $allValues += $arr;
    }
}

Upvotes: 0

Flavius Stef
Flavius Stef

Reputation: 13798

array_merge($bigArray['jobDescription'], $bigArray['userDetail']);

Upvotes: 1

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14882

You have two arrays stored in an array. You want the values of both arrays under one array instead of two subarrays?

$newArray = array_merge($array['jobDescription'], $array['userDetail']);

Upvotes: 4

user142162
user142162

Reputation:

I think you're looking for array_merge, which merges two arrays together:

$new_arr = array_merge($arr['jobDescription'], $arr['userDetail']);

Upvotes: 1

Related Questions