PHP Convert multidimensional array in one dimensional array of arrays [复制]

n3h0vuf2  于 2023-09-29  发布在  PHP
关注(0)|答案(3)|浏览(97)

此问题已在此处有答案

How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate](23个回答)
How to Flatten a Multidimensional Array?(31个回答)
Turning multidimensional array into one-dimensional array [duplicate](11个答案)
Merge all sub arrays into one [duplicate](3个答案)
Remove first levels of identifier in array [duplicate](7个回答)
2天前关闭。
我有15个元素的数组,每个元素包含1000个数组。我如何将所有这些数组转换为一个简单的维数组?我需要得到这个内部数组,并将其转换为一维数组的数组。

Array
(
    [0] => Array
        (
            [0] => Array[0..999]
            [1] => Array[0..999]
            [2] => Array[0..999]
        )

    [1] => Array
        (
            [0] => Array[0..999]///items are also arrays
            [1] => Array[0..999]
        )

    [2] => Array
        (

            [0] => Array[0..999]
            [1] => Array[0..999]
            [2] => Array[0..999]
        )
....

它需要看起来像这样:

Array(
[0] => Array
    [0]=>value
    [1]=>value
    [2]=>value

[1] => Array
    [0]=>value
    [1]=>value
    [2]=>value
)
xiozqbni

xiozqbni1#

array_merge()将合并多个数组,但主数组中有一个未指定的数字。因此,使用数组作为call_user_func_array()的参数,array_merge()作为回调函数:

$result = call_user_func_array('array_merge', $array);

从PHP 5.6开始使用参数解包:

$result = array_merge(...$array);
2nbm6dog

2nbm6dog2#

创建一个空的'main'数组,并将15个数组合并到其中

$main_array = [];

foreach($big_array as $value)
{
    $main_array = array_merge($main_array,$value);
}

例如:

$main_array = [];
foreach([[1],[2],[3,4,5,6,7]] as $value)
{
    $main_array = array_merge($main_array,$value);
}
print_r($main_array);

//output
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
)
9nvpjoqh

9nvpjoqh3#

一个递归函数,一个调用自己的函数,可以做到这一点,例如。

<?php

$currentArray = [*your multi-dim array*];
$targetArray = [];

$level = 0;

$targetArray = flattenArray($currentArray, $targetArray, $level);

function flattenArray($currentArray, $targetArray, $level){
  foreach($currentArray as $value){
    if(is_array($value) AND $level < 1){
      $targetArray = flattenArray($value, $targetArray, $level + 1);
    }else{
      $targetArray[] = array(print_r($value, TRUE));
    }
  }
  return $targetArray;
}

?>

相关问题