php 将多维数组转换为单个数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6785355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:14:20  来源:igfitidea点击:

Convert multidimensional array into single array

phparrays

提问by CuriousMind

I have an array which is multidimensional for no reason

我有一个无缘无故的多维数组

/* This is how my array is currently */
Array
(
[0] => Array
    (
        [0] => Array
            (
                [plan] => basic
            )

        [1] => Array
            (
                [plan] => small
            )

        [2] => Array
            (
                [plan] => novice
            )

        [3] => Array
            (
                [plan] => professional
            )

        [4] => Array
            (
                [plan] => master
            )

        [5] => Array
            (
                [plan] => promo
            )

        [6] => Array
            (
                [plan] => newplan
            )

    )

 )

I want to convert this array into this form

我想将此数组转换为这种形式

/*Now, I want to simply it down to this*/
Array (
[0] => basic
[1] => small
[2] => novice
[3] => professional
[4] => master
[5] => promo
[6] => newplan
)

Any idea how to do this?

知道如何做到这一点吗?

回答by AlienWebguy

Assuming this array may or may not be redundantly nested and you're unsure of how deep it goes, this should flatten it for you:

假设这个数组可能是也可能不是冗余嵌套的,并且您不确定它有多深,这应该为您展平它:

function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $result = array_merge($result, array_flatten($value)); 
    } 
    else { 
      $result[$key] = $value; 
    } 
  } 
  return $result; 
} 

回答by Usman Ahmed

This single line would do that:

这一行就可以做到:

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

The first argument is an array | The second argument is an array key.

第一个参数是一个数组 | 第二个参数是一个数组键。

For details, go to official documentation: https://www.php.net/manual/en/function.array-column.php.

详情请参考官方文档:https: //www.php.net/manual/en/function.array-column.php

回答by Paul

Just assign it to it's own first element:

只需将它分配给它自己的第一个元素:

$array = $array[0];

回答by wellsantos

If you come across a multidimensional array that is pure data, like this one below, then you can use a single call to array_merge() to do the job via reflection:

如果您遇到一个纯数据的多维数组,如下所示,那么您可以使用对 array_merge() 的单个调用通过反射来完成这项工作:

$arrayMult = [ ['a','b'] , ['c', 'd'] ];
$arraySingle = call_user_func_array('array_merge', $arrayMult);
// $arraySingle is now = ['a','b', 'c', 'd'];

回答by vikas

 $singleArray = array();

    foreach ($multiDimensionalArray as $key => $value){
        $singleArray[$key] = $value['plan'];
    }

this is best way to create a array from multiDimensionalArray array.

这是从 multiDimensionalArray 数组创建数组的最佳方法。

thanks

谢谢

回答by deceze

For this particular case, this'll do:

对于这种特殊情况,这将执行以下操作:

$array = array_map('current', $array[0]);

It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.

这基本上是完全相同的问题,看看那里的一些答案:PHP array merge from unknown number of parameters

回答by devnull Ψ

none of answers helped me, in case when I had several levels of nested arrays. the solution is almost same as @AlienWebguy already did, but with tiny difference.

没有任何答案对我有帮助,以防我有多个级别的嵌套数组。该解决方案与@AlienWebguy 已经完成的几乎相同,但差异很小。

function nestedToSingle(array $array)
{
    $singleDimArray = [];

    foreach ($array as $item) {

        if (is_array($item)) {
            $singleDimArray = array_merge($singleDimArray, nestedToSingle($item));

        } else {
            $singleDimArray[] = $item;
        }
    }

    return $singleDimArray;
}

test example

测试示例

$array = [
        'first',
        'second',
        [
            'third',
            'fourth',
        ],
        'fifth',
        [
            'sixth',
            [
                'seventh',
                'eighth',
                [
                    'ninth',
                    [
                        [
                            'tenth'
                        ]
                    ]
                ],
                'eleventh'
            ]
        ],
        'twelfth'
    ];

    $array = nestedToSingle($array);
    print_r($array);

    //output
    array:12 [
        0 => "first"
        1 => "second"
        2 => "third"
        3 => "fourth"
        4 => "fifth"
        5 => "sixth"
        6 => "seventh"
        7 => "eighth"
        8 => "ninth"
        9 => "tenth"
        10 => "eleventh"
        11 => "twelfth"
   ]

回答by Md. Maruf Hossain

You can do it just using a loop.

你可以只使用循环来做到这一点。

    $singleArray = array();

    foreach ($multiDimensionalArray as $key => $value){
        $singleArray[$key] = $value['plan'];
    }

回答by Joshua M

Recently I've been using AlienWebguy's array_flatten function but it gave me a problem that was very hard to find the cause of.
array_merge causes problems, and this isn't the first time that I've made problems with it either.
If you have the same array keys in one inner array that you do in another, then the later values will overwrite the previous ones in the merged array.

最近我一直在使用 AlienWebguy 的 array_flatten 函数,但它给了我一个很难找到原因的问题。
array_merge 会导致问题,这也不是我第一次遇到问题。
如果一个内部数组中的数组键与另一个数组中的数组键相同,则后面的值将覆盖合并数组中的前一个值。

Here's a different version of array_flatten without using array_merge:

这是不使用 array_merge 的不同版本的 array_flatten:

function array_flatten($array) { 
  if (!is_array($array)) { 
    return FALSE; 
  } 
  $result = array(); 
  foreach ($array as $key => $value) { 
    if (is_array($value)) { 
      $arrayList=array_flatten($value);
      foreach ($arrayList as $listItem) {
        $result[] = $listItem; 
      }
    } 
   else { 
    $result[$key] = $value; 
   } 
  } 
  return $result; 
} 

回答by mickmackusa

Your sample array has 3 levels. Because the first level has only [0], you can hardcode your access into it and avoid an extra function/construct call.

您的样本数组有 3 个级别。因为第一级只有[0],您可以将您的访问硬编码到其中并避免额外的函数/构造调用。

(Code Demos)

代码演示

  1. array_walk_recursive()is handy and versatile, but for this task may be overkill and certainly a bit more convoluted in terms of readability.

    array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
    var_export($flat);
    
  2. If this was my code, I'd be using array_column()because it is direct and speaks literally about the action being performed.

    var_export(array_column($array[0], 'plan'));
    
  3. Of course a couple of `foreach() loopswill perform very efficiently because language constructs generally perform more efficiently than function calls.

    foreach ($array[0] as $plans) {
        foreach ($plans as $value) {
            $flat[] = $value;
        }
    }
    var_export($flat);
    
  4. Finally, as a funky alternative (which I can't imagine actually putting to use unless I was writing code for someone whom I didn't care for) I'll offer an array_merge_recursive() call with a splat operator(...).

    var_export(array_merge_recursive(...$array[0])['plan']);
    
  1. array_walk_recursive()既方便又通用,但对于这项任务来说可能有点矫枉过正,而且在可读性方面肯定有点复杂。

    array_walk_recursive($array, function($leafvalue)use(&$flat){$flat[] = $leafvalue;});
    var_export($flat);
    
  2. 如果这是我的代码,我会使用array_column()因为它是直接的,并且从字面上谈论正在执行的操作。

    var_export(array_column($array[0], 'plan'));
    
  3. 当然,几个 `foreach() 循环将非常有效地执行,因为语言结构通常比函数调用执行得更有效。

    foreach ($array[0] as $plans) {
        foreach ($plans as $value) {
            $flat[] = $value;
        }
    }
    var_export($flat);
    
  4. 最后,作为一个时髦的替代方案(我无法想象实际使用它,除非我正在为我不关心的人编写代码),我将提供一个带有 splat 运算符( ...)的array_merge_recursive() 调用

    var_export(array_merge_recursive(...$array[0])['plan']);