13

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Karan Adhikari
  • 485
  • 1
  • 5
  • 16
  • 1
    it coming dynamically using mysql queries. what would you see in html ?@AbdulWaheed – Karan Adhikari Jan 11 '17 at 11:03
  • Show the code that creates the first array, that is where your issue is – RiggsFolly Jan 11 '17 at 11:04
  • 1
    Possible duplicate of [Turning multidimensional array into one-dimensional array](http://stackoverflow.com/questions/8611313/turning-multidimensional-array-into-one-dimensional-array) – Rahul Jan 11 '17 at 11:21
  • @Mohammad, Just curious, What extra `information / requirements` are you trying to obtain that hasn't already been provided? Obviously, we haven't provided what you really want, as a solution? – Ryan Vincent Feb 05 '17 at 15:16
  • @RyanVincent The question has multiple answer contain diverse solution. But i think this question is hepful for others and *has not received enough attention*. I used `bounty` to show question to another user and receive new solutions. – Mohammad Feb 05 '17 at 15:29
  • @RyanVincent I said, *show question to another user and receive new solutions*. If new solution does not exist, so new answer doesn't posted. But another users see the question. – Mohammad Feb 05 '17 at 15:40
  • @Mohammad, just curious. How will you judge which answer gets the bonus? – Ryan Vincent Feb 05 '17 at 15:41
  • @RyanVincent Stackoverflow will judge. [*The highest voted answer started with a minimum score of 2 will be awarded the bounty*](http://stackoverflow.com/help/bounty) – Mohammad Feb 05 '17 at 15:46
  • @Mohammad, thanks for the clarification. – Ryan Vincent Feb 05 '17 at 15:47

18 Answers18

10

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
Dimitrios Desyllas
  • 9,082
  • 15
  • 74
  • 164
Azeez Kallayi
  • 2,567
  • 1
  • 15
  • 19
5

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.

Sunil Verma
  • 2,490
  • 1
  • 14
  • 15
5

Assuming that source array is array of arrays and it has no the same keys:

<?php
$src = [
    ['t1'=>'test1'],
    ['t2'=>'test2'],
    ['t3'=>'test3'],
    ['t4'=>'test4'],
    ['t5'=>'test5'],
];
$result = call_user_func_array('array_merge', $src);

result via var_dump():

array(5) {
  ["t1"]=>
  string(5) "test1"
  ["t2"]=>
  string(5) "test2"
  ["t3"]=>
  string(5) "test3"
  ["t4"]=>
  string(5) "test4"
  ["t5"]=>
  string(5) "test5"
}
Wizard
  • 862
  • 6
  • 9
3

You can use array_reduce() to change values of array. In callback get key of item using key() and select first item using reset().

$newArr = array_reduce($oldArr, function($carry, $item){
    $carry[key($item)] = reset($item);
    return $carry;
});

Check result in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
3

Try this function,

function custom_function($input_array)
{
    $output_array = array();
    for ($i = 0; $i < count($input_array); $i++) {
        for ($j = 0; $j < count($input_array[$i]); $j++) {
            $output_array[key($input_array[$i])] = $input_array[$i][key($input_array[$i])];
        }
    }
    return $output_array;
}

$arr = custom_function($arr);
print_r($arr);

Give it a try, it will work.

Rahul
  • 18,271
  • 7
  • 41
  • 60
2

You can use this

<?php
$temp = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));

$result_array = array();
foreach ($temp as $val) {
  foreach ($val as $key => $inner_val) {
    $result_array[$key] = $inner_val;
  }
}
print_r($result_array);

?>
sujivasagam
  • 1,659
  • 1
  • 14
  • 26
2
// Multidimensional array
$arrdata = Array(
    '0' => Array(
        't1' => 'test1'
    ) ,
    '1' => Array(
        't2' => 'test2'
    ) ,
    '2' => Array(
        't3' => 'test3'
    )
);

// Convert to a single array
$data = array();
foreach($arrdata as $key => $value) {
    foreach($value as $key1 => $value1) {
        $data[$key1] = $value1;
    }
}
echo $data;
Al.G.
  • 4,327
  • 6
  • 31
  • 56
2

For your specific case, I would use array_reduce where I set the initial value with an empty array

array_reduce($arr, function($last, $row) {
    return $last + $row;
}, array());

AFTER PHP 7.4

array_reduce($arr, fn ($last, $row) => $last + $row, []);

Result :

[
    't1' => 'test1',
    't2' => 'test2',
    't3' => 'test3',
    't4' => 'test4',
    't5' => 'test5'
]
beta-developper
  • 1,689
  • 1
  • 13
  • 24
2

Try array map function.

$singleDimensionArray = array_map('current',$multiDimensionArray);
vivek s vamja
  • 1,001
  • 10
  • 11
2

You can use this if you don't care about keeping the correct array keys

function flattenA(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}
print_r(flattenA($arr));
// Output
Array
(
    [0] => test1
    [1] => test2
    [2] => test3
    [3] => test4
    [4] => test5
)

Otherwise

function flattenB(array $array) {
    $return = array();
    array_walk_recursive($array, function($v,$k) use (&$return) { $return[$k] = $v; });
    return $return;
}
print_r(flattenB($arr));
// Output
Array
(
    [t1] => test1
    [t2] => test2
    [t3] => test3
    [t4] => test4
    [t5] => test5
)

Check both on Sandbox

From answer on similar question

Community
  • 1
  • 1
Nick Kuznia
  • 1,698
  • 17
  • 27
  • Made an edit to match OP question better by keeping the correct array keys in output. –  Feb 11 '17 at 20:54
1

Hey @Karan Adhikari Simple like below one:

<?php
    $arr1 = array(array("t1" => "test1"), array("t2" => "test2"), array("t3" => "test3"), array("t4" => "test4"), array("t5" => "test5"));
    echo "<pre>";
    print_r($arr1);//before
    $arr2 = array();
    foreach($arr1 as $val){ 
        $arr2 = array_merge($arr2, $val);
    }
    echo "<pre>";
    print_r($arr2); // after you get your answer
lazyCoder
  • 2,544
  • 3
  • 22
  • 41
1

Please try this function:

function array_merging($multi_array) { 
    if (is_array($multi_array)) { 
        $new_arr = array(); 
        foreach ($multi_array as $key => $value) { 
            if (is_array($value)) { 
            $new_arr = array_merge($new_arr, array_merging($value)); 
            } 
            else { 
                $new_arr[$key] = $value; 
            } 
        } 
        return $new_arr; 
    }
    else {
        return false;
    }
}

Use this function:

$your_multi_arr = array(array(array('t1'=>'test1'),array('t2'=>'test2'),array('t3'=>'test3'),array('t4'=>'test4')));
$arr1 = array_merging($your_multi_arr);
echo "<pre>";
print_r($arr1);

Hope, this may be useful for you.

Prateek Verma
  • 869
  • 1
  • 6
  • 9
1

You can try traversing the array using PHP while list and each. I took sample code from PHP website the second example you can check it here

$arr = [['t1' => 'test1'],['t2' => 'test2'],['t3' => 'test3'],['t4' => 'test4'],['t5' => 'test5']];
$output = [];
while (list($key, $val) = each($arr)) {
    while (list($k, $v) = each($val)) {
    $output[$k] = $v;
}
}
print_r($output);

Output created is

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

You can test it on your own in this Sandbox example.

1

This will do the trick

$array = array_column($array, 't1');

Note: This function array_column introduced in PHP 5.5 so it won't work in earlier versions.

G.Ashok Kumar
  • 1,649
  • 2
  • 13
  • 25
0

traverse the array and save the key value, Live Demo here.

<?php
    $array = array(array('t1' => 'test1'), array('t2' => 'test2'), array('t3' => 'test3'), array('t4' => 'test4'), array('t5' => 'test5'));
    $result = [];
    array_walk($array, function($value) use(&$result){
        foreach($value as $k => $v)
        {
            $result[$k] = $v;
        }
    });
    var_dump($result);
LF00
  • 27,015
  • 29
  • 156
  • 295
0
`$result = "Query";  $key_value = array();`

      foreach ($result as $key => $value) {
          $key_value[$key['']] = $value[''];
      }
     //for checking //echo "<pre>" ; print_r($key_value) ; exit;
      return $key_value;

pls fill $key['name given in sql query for field'] and $value['name given in sql query for field'] (both are same)

0

this works for me

 $result = [];
              foreach($excelEmails as $arr)
              {
                  foreach ($arr as $item){
                      $result = array_merge($result , $item);
                  }
              }
              dd($result);
Ajmal
  • 99
  • 1
  • 6
-1

i would recomment my way to convert all double-dimensional array to single-dimensional array.

<?php

  $single_Array = array();

  //example array
  $array = array(
    array('t1' => 'test1'), 
    array('t2' => 'test2'), 
    array('t3' => 'test3'), 
    array('t4' => 'test4'), 
    array('t5' => 'test5'));

 $size = sizeof($array);

 //loop to fill the new single-dimensional array
 for($count = 0; $count<sizeof($array);$count++)
 {
    //take the key of multi-dim array
    $second_cell = key($array[$count]);
    //set the value into the new array
    $single_array[$count] = $array[$count][$second_cell];
 }

 //see the results
 var_dump($single_array);


?>

with this script we can take keys and values to create new single-dimensional array.I hope that i was helpfull to you.

you can see the example here: Array Convert Demo

rtroulak
  • 459
  • 1
  • 8
  • 16