How to convert multi-dimensional array into single array using PHP?

Karan Adhikari picture Karan Adhikari · Jan 11, 2017 · Viewed 9.6k times · Source

After implementing database queries, I am getting the multi-dimensional array below.

Two Dimensional Array

Array
(
    [0] => Array
        (
            [t1] => test1
        )

    [1] => Array
        (
            [t2] => test2
        )

    [2] => Array
        (
            [t3] => test3
        )

    [3] => Array
        (
            [t4] => test4
        )

    [4] => Array
        (
            [t5] => test5
        )

)

but I want to convert it to a single dimensional array, like the format below:

One Dimensional Array

Array (
    t1 => test1
    t2 => test2
    t3 => test3
    t4 => test4
    t5 => test5
)

How can I do this?

Answer

Azeez Kallayi picture Azeez Kallayi · Jan 11, 2017

I think you can use array_reduce() function. For example:

   $multi= array(0 => array('t1' => 'test1'),1 => array('t2' => 'test2'),2 => array('t3' => 'test3'),3 => array('t4' => 'test4'));
   $single= array_reduce($multi, 'array_merge', array());
   print_r($single);  //Outputs the reduced aray