Converting a nested array to single dimensional array
我有一个数组:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
我想转换成
1 2 3 4 5 |
号
我写了这样一个函数:
1 2 3 4 5 6 7 | foreach($arr as $a) { foreach($a as $k=>$sub) { $newArr[$k] = $sub; } } |
我做得对吗?
记住,数组合并和数组+数组有什么区别?
在"endresult"数组上使用+=将把给定的数组添加到当前数组中。上面的链接中解释了一些注意事项,以防键重叠。
1 2 3 4 5 6 7 | $arr = [[2012 => 'foo'],[2014 => 'bar'],[2015=>'baz']]; $new = []; foreach($arr as $i) { $new += $i; } echo"[cc lang="php"]"; var_dump($new); |
现场样品:https://ideone.com/olydnq
请检查此代码,它也适用于非组合数组结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | <?php $array = array ( 'aaaaa', 10, '0' => array ( '2010' => 2010, ), '1' => array ( '2011' => 2011, ), '2' => array ( '2012' => 2012, ), '3' => array ( '2013' => 2013, ), '4' => array ( '2014' => 2014, ), '5' => array ( '2015' => 2015, ), '6' => array ( '2016' => 2016, '2017' => 2017, 'xxxx' => 'yyyy', ), ); $newArr=array(); function walk_first($val, $key) { if(is_array($val)) { array_walk($val, 'walk_second'); } } function walk_second($val, $key) { global $newArr; $newArr[$key]=$val; } array_walk($array, 'walk_first'); print_r($newArr); ?> |
请试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | $array = Array ( '0' => Array ( '2010' => 2010, ), '1' => Array ( '2011' => 2011, ), '2' => Array ( '2012' => 2012, ), '3' => Array ( '2013' => 2013, ), '4' => Array ( '2014' => 2014, ), '5' => Array ( '2015' => 2015, ), '6' => Array ( '2016' => 2016, ), ); $oneDimensionalArray = call_user_func_array('array_merge', $array); foreach($oneDimensionalArray as $_oneDimensionalArray) { $newArr[$_oneDimensionalArray] = $_oneDimensionalArray; } print_r($newArr) |
号