Sahithya Sahithya - 3 months ago 11
PHP Question

Array within array as single associative array

I am having array within array values as below.

Array
(
[0] => Array
(
[0] => Array
(
[Floor] => Floor-1
)

[1] => Array
(
[Flat] => Flat A2
)

[2] => Array
(
[Area] => Balcony,
)

)
)


I need to make it as single associative array as below.

Array
(
[0] => Array
(
[Floor] => Floor-1
[Flat] => Flat A2
[Area] => Balcony,
)
)


How can i do this ?

Answer

This example should help you.

<?php


$arr = array(
    array(
        'floor'=>'Floor-1'
        ),
    array(
        'Flat'=>'Flat A2'
        ),
    array(
        'Area'=>'Balcony,'
        ),
    );



$final_array = array();
foreach ($arr as $arr1) {

    foreach ($arr1 as $key => $value) {
        $final_array[$key] = $value;
    }

}


?>

Output will be

 Array
    (
        [floor] => Floor-1
        [Flat] => Flat A2
        [Area] => Balcony,
    )

Here we have created an empty array called as $final_array we will append this array by using foreach loop.

Remember, if you have a same array key then the last value will overwrite like below.

<?php
$arr = array(
    array(
        'floor'=>'Floor-1',
        'floor'=>'Floor-2',
        ),
    array(
        'Flat'=>'Flat A2'
        ),
    array(
        'Area'=>'Balcony,'
        ),

     array(
        'Area'=>'Balcony2,'
        ),
    );



$final_array = array();
foreach ($arr as $arr1) {

    foreach ($arr1 as $key => $value) {
        $final_array[$key] = $value;
    }

}


?>

Now, output will be

Array
(
    [floor] => Floor-2
    [Flat] => Flat A2
    [Area] => Balcony2,
)