简体   繁体   English

如何使用php将多维数组转换为单个数组?

[英]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
)

Please help me to do so 请帮我这样做

I think you can use array_reduce() function. 我认为您可以使用array_reduce()函数。 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

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. 其中$ arrayData是您的数据库数据数组,而$ newArray将是结果。

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(): 通过var_dump()得到的结果:

array(5) {
  ["t1"]=>
  string(5) "test1"
  ["t2"]=>
  string(5) "test2"
  ["t3"]=>
  string(5) "test3"
  ["t4"]=>
  string(5) "test4"
  ["t5"]=>
  string(5) "test5"
}

You can use array_reduce() to change values of array. 您可以使用array_reduce()更改数组的值。 In callback get key of item using key() and select first item using reset() . 在回调中,使用key()获取项目的key()并使用reset()选择第一个项目。

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

Check result in demo 演示中检查结果

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. 试试看,它将起作用。

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

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 从类似问题的答案

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

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

尝试数组映射功能。

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

For your specific case, i would use array_reduce where i set the init value by an empty array 对于您的特定情况,我将使用array_reduce ,其中我通过一个空数组设置初始值

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

AFTER PHP 7.4 PHP 7.4之后

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

Result : 结果:

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

Hey @Karan Adhikari Simple like below one: 嘿@Karan Adhikari简单如下所示:

<?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

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. 希望这对您有用。

You can try traversing the array using PHP while list and each . 您可以尝试使用PHP while listeach遍历数组。 I took sample code from PHP website the second example you can check it here 我从PHP网站上获取了示例代码,第二个示例可以在此处查看

$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. 您可以在此沙盒示例中自行进行测试

traverse the array and save the key value, Live Demo here . 遍历数组并保存键值, 此处为Live Demo

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

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. 注意:此函数array_column在PHP 5.5中引入,因此在早期版本中将不起作用。

`$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) 请填写$ key ['在字段的sql查询中给定的名称']$ value ['在sql的查询字段中给定的名称'] (两者相同)

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 您可以在此处看到示例: 数组转换演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM