欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

求解数组合并

程序员文章站 2022-06-17 15:10:05
...
Array ( [59] =>aa [17] => bb [18] =>cc [69] => dd [21] =>ee [22] => ss [23] => Array ( [0] => 1a[1] =>2a[2] => 3a [3] =>4a [4] => 55 ) [24] =>vv [26] => va [43] => Array ( [0] => 道 [1] =>向 [2] => 圾 [3] => 灯 [4] => 速 [5] => 灯 [6] => 则 ) [53] => 元 [54] => 995 )[1]=>Array ( [59] =>aa [17] => bb [18] =>cc [69] => dd [21] =>ee [22] => ss [23] => Array ( [0] => 1a[1] =>2a[2] => 3a [3] =>4a [4] => 55 ) [24] =>vv [26] => va [43] => Array ( [0] => 道 [1] =>向 [2] => 圾 [3] => 灯 [4] => 速 [5] => 灯 [6] => 则 ) [53] => 元 [54] => 995 )
如何将最后一维合并?
是用foreach遍历时合并吗?如果数据多了会不会卡住?


回复讨论(解决方案)

你所谓的合并是什么意思呢?哪个合并到哪个?

你所谓的合并是什么意思呢?哪个合并到哪个?


Array ( [59] =>aa [17] => bb [18] =>cc [69] => dd [21] =>ee [22] => ss [23] => Array ( [0] => 1a[1] =>2a[2] => 3a [3] =>4a [4] => 55 ) [24] =>vv [26] => va [43] => Array ( [0] => 道 [1] =>向 [2] => 圾 [3] => 灯 [4] => 速 [5] => 灯 [6] => 则 ) [53] => 元 [54] => 995 )[1]=>Array ( [59] =>aa [17] => bb [18] =>cc [69] => dd [21] =>ee [22] => ss [23] => Array ( [0] => 1a[1] =>2a[2] => 3a [3] =>4a [4] => 55 ) [24] =>vv [26] => va [43] => Array ( [0] => 道 [1] =>向 [2] => 圾 [3] => 灯 [4] => 速 [5] => 灯 [6] => 则 ) [53] => 元 [54] => 995 )
合并成例如[23]=>2a,3a,4a,55..........

foreach($arr as $k=>$v){        if(is_array($v)) $arr[$k] = implode(',', $v);}print_r($arr);

foreach($arr as $k=>$v){        if(is_array($v)) $arr[$k] = implode(',', $v);}print_r($arr);

如果是三维数组合并第三维是不是这样
foreach($arr as $k=>$v){foeach($v as $key=>$val){        if(is_array($val)) $v[$key] = implode(',', $val);}}

不一定,需判断 $v 是数组后,方可进入 foeach($v as ...

$v[$key] = implode(',', $val);
改为:
$arr[$k][$key] = implode(',', $val);

且你需要判断一下$v 是数组后才能遍历$v , 否则会报错。

不一定,需判断 $v 是数组后,方可进入 foeach($v as ...


正如你所说我失败了
array(
[0]=>
array([8]=>aa[9]=> array([77]=>bb[88]=>cc)合并成:bb,cc[10]=>44
)
.................
)
....................
最终实现转成二维数组。。。然后导出excel
最终数组练的让我头痛,还没完全撑握

应该这样写

$a = array(  0 => array(    8 => 'aa',    9 => array(      77 => 'bb',      88 => 'cc',    ),    10 => 44,  ),);$a = dimension_reduction($a); //执行一次降一次维print_r($a);$a = dimension_reduction($a);print_r($a);//降维function dimension_reduction($ar) {  $flag = 1;  foreach($ar as $k=>$v) {    if(is_array($v)) {      $flag = 0;      $ar[$k] = dimension_reduction($v);    }  }  if($flag) return join(',', $ar);  return $ar;}
Array
(
[0] => Array
(
[8] => aa
[9] => bb,cc
[10] => 44
)

)
Array
(
[0] => aa,bb,cc,44
)