将多维数组转换为单一数组。

71

我有一个数组,它是多维的,但没有任何原因

/* 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
            )

    )

 )

我想将这个数组转换成这种形式

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

有什么方法可以实现这个?


1
有没有什么原因导致它是这样的?而不是改变数组,有没有一种方法可以在一开始就以不同的方式创建数组? - erisco
希望这对您有所帮助,$array=[ 0 => [ 0 => ['plan' => 'basic'], 1 => ['plan' => 'small'], 2 => ['plan' => 'novice'], 3 => ['plan' => 'professional'], 4 => ['plan' => 'master'], 5 => ['plan' => 'promo'], 6 => ['plan' => 'newplan'] ] ]; $arr=[]; array_walk_recursive($array, function($k){global $arr; $arr[]=$k;}); print_r($arr); - Piyush Sapariya
24个回答

134

3
不错,但需要 PHP 5 >= 5.5.0 版本支持:https://php.net/manual/en/function.array-column.php - Matt V.
只有在需要特定键的值时才有用。 - devnull Ψ
@devnull-Ψ 这就是他在问题中所询问的。 - Usman Ahmed

114

假设该数组可能会或可能不会嵌套重复,且您不确定其深度,那么此代码将帮助您将其展平:

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

30
如果你遇到一个如下所示的纯数据的多维数组,那么你可以使用反射来进行一次调用array_merge()完成操作:

如果您遇到一个纯数据的多维数组,就像下面这个例子一样,那么您可以使用一次反射调用array_merge()来完成操作:

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

如果有人需要了解更多关于'call_user_func_array'的内容,这里是官方文档链接:https://www.php.net/manual/en/function.call-user-func-array.php - Ali
3
你可以使用 $arraySingle = array_merge(...$arrayMult); 实现。 - Peacefull
@Peacefull 我看到你正在正确地使用 PHPStorm! - Yonn Trimoreau

15
只需将它分配给自己的第一个元素即可:
$array = $array[0];

@Usman Ahmed 再次查看原始数组。所有七个元素都在一个仅有一个元素的数组中。 - Paul
1
这将输出: 数组 ( [0] => 数组 ( [plan] => 基本 ) [1] => 数组 ( [plan] => 小型 ) [2] => 数组 ( [plan] => 新手 ) )这不是他想要的。 - Usman Ahmed
它将返回以下数组,这不是用户想要的。 - Usman Ahmed
需要修改了 @Paul 这个答案是完全错误的。 - mickmackusa

9
对于这个特定情况,这样做就可以了:
$array = array_map('current', $array[0]);

这基本上是与这个问题完全相同,可以查看那里的一些答案:PHP从未知数量的参数合并数组


它不仅适用于数组的“0”元素,而且适用于任何数组。谢谢,兄弟,它有效。@deceze - Prasad Patel

8
 $singleArray = array();

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

这是从多维数组创建数组的最佳方法。谢谢。

8

问题数组:

array:2 [▼
  0 => array:3 [▼
    0 => array:4 [▼
      "id" => 8
      "name" => "Veggie Burger"
      "image" => ""
      "Category_type" => "product"
    ]
    1 => array:4 [▼
      "id" => 9
      "name" => "Veggie Pitta"
      "image" => ""
      "Category_type" => "product"
    ]
    2 => array:4 [▼
      "id" => 10
      "name" => "Veggie Wrap"
      "image" => ""
      "Category_type" => "product"
    ]
  ]
  1 => array:2 [▼
    0 => array:4 [▼
      "id" => 18
      "name" => "Cans 330ml"
      "image" => ""
      "Category_type" => "product"
    ]
    1 => array:4 [▼
      "id" => 19
      "name" => "Bottles 1.5 Ltr"
      "image" => ""
      "Category_type" => "product"
    ]
  ]
]

解决方案数组:

array:5 [▼
  0 => array:4 [▼
    "id" => 8
    "name" => "Veggie Burger"
    "image" => ""
    "Category_type" => "product"
  ]
  1 => array:4 [▼
    "id" => 9
    "name" => "Veggie Pitta"
    "image" => ""
    "Category_type" => "product"
  ]
  2 => array:4 [▼
    "id" => 10
    "name" => "Veggie Wrap"
    "image" => ""
    "Category_type" => "product"
  ]
  3 => array:4 [▼
    "id" => 18
    "name" => "Cans 330ml"
    "image" => ""
    "Category_type" => "product"
  ]
  4 => array:4 [▼
    "id" => 19
    "name" => "Bottles 1.5 Ltr"
    "image" => ""
    "Category_type" => "product"
  ]
]

写下这段代码,获取你的解决方案,$subcate 是你的多维数组。

$singleArrayForCategory = array_reduce($subcate, 'array_merge', array());

5

没有一个答案对我有帮助,因为我的问题是在嵌套多层级的数组中。解决方案几乎和@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;
}

测试示例

$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"
   ]

4

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

(代码演示)

  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() loops will 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']);
    

3

最近我一直在使用AlienWebguy的array_flatten函数,但它给了我一个非常难以找到原因的问题。
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; 
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接