如何将多维数组转换为单个数组

时间:2019-01-05 03:39:40

标签: php

我有一个动态的多维数组,如下所示:

Array ( 
    [1] => Array ( [0] => 63 [1] => 60 [2] => 67 [3] => 58 [4] => 35 [5] => 47 [6] => 30 [7] => 47 [8] => 61 [9] => 63 [10] => 56 [11] => 56 [12] => 44 [13] => 38 [14] => 36 [15] => 45 [16] => 39 [17] => 55 [18] => 60 [19] => 45 [20] => 37 [21] => 45 [22] => 63 [23] => 62 [24] => 50 [25] => 47 [26] => 46 [27] => 37 [28] => 69 [29] => 35 [30] => 33 [31] => 65 [32] => 63 [33] => 50 [34] => 69 [35] => 43 [36] => 65 [37] => 64 [38] => 45 [39] => 65 [40] => 43 [41] => 30 [42] => 51 [43] => 28 [44] => 33 [45] => 53 [46] => 67 [47] => 28 [48] => 47 [49] => 42 [50] => 49 ) 
    [2] => Array ( [0] => 30 [1] => 30 [2] => 27 [3] => 29 [4] => 29 [5] => 29 [6] => 27 [7] => 28 [8] => 30 [9] => 29 [10] => 29 [11] => 29 [12] => 29 [13] => 28 [14] => 30 [15] => 29 [16] => 29 [17] => 28 [18] => 30 [19] => 27 [20] => 28 [21] => 27 [22] => 29 [23] => 30 [24] => 30 [25] => 28 [26] => 30 [27] => 29 [28] => 30 [29] => 27 [30] => 27 [31] => 27 [32] => 29 [33] => 29 [34] => 30 [35] => 28 [36] => 29 [37] => 29 [38] => 28 [39] => 30 [40] => 28 [41] => 28 [42] => 28 [43] => 28 [44] => 30 [45] => 27 [46] => 28 [47] => 27 [48] => 30 [49] => 27 [50] => 29 ) ) 

我想将其转换为此输出数组:

Array (
    [0] => 63,30
    .....
    [50] => 49,29
    )

1 个答案:

答案 0 :(得分:1)

此代码将为您提供所需的答案。它使用array_keys找到数组第一个元素的键,然后使用array_column为数组中的每个条目获取该键的值。 array_column的结果是implode,以便为新数组提供所需的值:

$newarray = array();
$keys = array_keys(array_values($array)[0]);
foreach ($keys as $key) {
    $newarray[$key] = implode(',', array_column($array, $key));
}
print_r($newarray);

输出:

Array (
    [0] => 63,30
    [1] => 60,30
    [2] => 67,27
    [3] => 58,29
    ...
    [50] => 49,29 
)

Demo on 3v4l.org