php数组的升维和降维处理
最近学习了一下php数组的升维和降维,废话少说,上Demo。
//假设有数组降维前,如下 $array = array( 'a' => array( 'b' => 1, 'c' => array( 'd' => 2, 'e' => 3 ) ), 'f' => 4, 'g' => array( 'h'=>5 ) );
降维后,如下:
//降维后 $array = array( '0' => a->b->1, '1' => a->c->d->2, '2' => a->c->e->3, '3' => f->4, '4' => g->h->5 );
实现的function如下:
/** * 将多维数组降维成一维数组,递归实现 * @param unknown $arr * @param string $delimiter * @param string $key * @return boolean|Ambigous <multitype:string , multitype:> */ function multiToSingle($arr, $delimiter = '->',$key = ' ') { $resultAry = array(); if (!(is_array($arr) && count($arr)>0)) { return false; } foreach ($arr AS $k=>$val) { $newKey = trim($key . $k . $delimiter); if (is_array($val) && count($val)>0) { $resultAry = array_merge($resultAry, multiToSingle($val, $delimiter, $newKey)); } else { $resultAry[] = $newKey . $val; } } return $resultAry; }
数组有降必有升,升维来了:
/** * 将一维数组升维成多维数组 * * @param unknown $arr * @param string $delimiter * @return multitype: */ function singleToMulti($arr, $delimiter = '->') { if (! (is_array ( $arr ) && count ( $arr ) > 0)) { return false; } $endAry = array (); foreach ( $arr as $key => $val ) { $sAry = explode ( $delimiter, $val ); $len = count ( $sAry ); $ary = array (); for($i = $len - 2; $i > - 1; $i --) { if ($i == $len - 2) { $ary [$sAry [$i]] = $sAry [$i + 1]; } else { $ary = array ( $sAry [$i] => $ary ); } } $endAry = array_merge_recursive ( $endAry, $ary ); } return $endAry; }
实现了数组的升维和降维,也许实现方式不够好,请批评指正!
如果不曾相逢,心绪不会如此沉重