How to convert multi-dimensional array into single

2019-02-16 13:36发布

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
)

Please help me to do so

18条回答
做自己的国王
2楼-- · 2019-02-16 14:02

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
查看更多
不美不萌又怎样
3楼-- · 2019-02-16 14:03
`$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)

查看更多
一纸荒年 Trace。
4楼-- · 2019-02-16 14:04

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.

查看更多
疯言疯语
5楼-- · 2019-02-16 14:06

Try array map function.

$singleDimensionArray = array_map('current',$multiDimensionArray);
查看更多
狗以群分
6楼-- · 2019-02-16 14:07

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.

查看更多
爷、活的狠高调
7楼-- · 2019-02-16 14:08

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);

?>
查看更多
登录 后发表回答