Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 468
Karan Adhikari Avatar asked Jan 11 '17 11:01

Karan Adhikari


People also ask

How do I convert multiple arrays into one array?

The array_merge() function merges one or more arrays into one array.

How do you make a single array?

const arr = [ [ {"c": 1},{"d": 2} ], [ {"c": 2},{"d": 3} ] ]; We are required to write a JavaScript function that takes in one such array as the first and the only argument. The function should then convert the array (creating a new array) into array of objects removing nested arrays.

How we can convert a multidimensional array to string without any loop?

Multidimensional PHP Array to String Maybe in case you need to convert a multidimensional array into a string, you may want to use the print_r() function. This is also called “array with keys”. By adding “true” as its second parameter, all the contents of the array will be cast into the string. <?


2 Answers

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
like image 55
Azeez Kallayi Avatar answered Oct 23 '22 02:10

Azeez Kallayi


You can use as follows :

$newArray = array();
foreach($arrayData as $key => $value) {
    foreach($value as $key2 => $value2) {
        $newArray[$key2] = $value2;
    }
}

Where $arrayData is your DB data array and $newArray will be the result.

like image 5
Sunil Verma Avatar answered Oct 23 '22 02:10

Sunil Verma