How to convert multi-dimensional array into single

2019-02-16 13:31发布

问题:

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

回答1:

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


回答2:

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.



回答3:

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"
}


回答4:

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



回答5:

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.



回答6:

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



回答7:

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

?>


回答8:

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


回答9:

try something like this For your limited use case, this'll do it:

$oneDimensionalArray = array_map('current', $twoDimensionalArray);

This can be more generalized for when the subarrays have many entries to this:

$oneDimensionalArray = call_user_func_array('array_merge', $twoDimensionalArray);


回答10:

Try array map function.

$singleDimensionArray = array_map('current',$multiDimensionArray);


回答11:

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


回答12:

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.



回答13:

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.



回答14:

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


回答15:

For your specific case, i would use array_reduce where i set the init value by an empty array

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

Result :

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


回答16:

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.



回答17:

`$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)



回答18:

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