DMS-KH
DMS-KH

Reputation: 2797

How to merges multi-dimensional array to single dimensional array in PHP

I want to merges all the values from identification,general,address,employer array to the single line of $aa array as below format.

the original array to merges.

  $aa = [
        0 => [
            'identification' => [
                1 => ['Iden_type' => 'types'],
                2 => ['Iden_num' => '000215'],
            ],
            'general' => [
                1 => ['gen_name' => 'name'],
                2 => ['gen_lname' => 'lname'],
            ],
            'address' => [
                1 => ['add_type' => 'type'],
                2 => ['add_text' => 'text'],
            ],
            'contact' => [
                1 => ['cont_type' => 'types'],
                2 => ['cont_text' => 'text'],
            ],
            'employer' => [
                1 => ['emp_fname' => 'first name'],
                2 => ['emp_lname' => 'last name'],
            ],

        ]
    ];

Result that I want to get from above array.

 $aa = [
        0 => [
            'types',
            '000215',
            'name',
            'lname',
            'type',
            'text',
            'types',
            'text',
            'first name',
            'last name',

        ],
        1 => [
            'types',
            '000215',
            'name',
            'lname',
            'type',
            'text',
            'types',
            'text',
            'first name',
            'last name',

        ],

    ];

Upvotes: 0

Views: 94

Answers (1)

Manh Nguyen
Manh Nguyen

Reputation: 940

foreach ($aa as $k => $v) {
    $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($v));
    foreach ($it as $value) {
        $result[$k][] = $value;
    }
}

SEE WORKING DEMO

Upvotes: 1

Related Questions