时间:2021-07-01 10:21:17 帮助过:1人阅读
以下代码$result = array( 'x' => 'xxx', 'y' => 'yyy',);$aList = array(55,99,77,44); //对应id字段,实际上个数不可预料$bList = array('1-20', '3-55', '88-99', '40-45'); //对应percent字段,个数不可预料,但和aList元素个数相同//................//................//要将第二和第三个数组加工到第一个数组里,形成这样的结果,一下子想不清楚,有点急着完成~谢谢了/*$result = array( 'x' => 'xxx', 'y' => 'yyy', 'other' = array( 'id' => 55, 'percent' => '1-20', 'other' => array( 'id' => 99, 'percent' => '3-55', 'other' => array( 'id' => 77, 'percent' => '88-99', 'other' => array( 'id' => 44, 'percent' => '40-45', ), ), ), ),);*/
$result = array( 'x' => 'xxx', 'y' => 'yyy',);$aList = array(55,99,77,44);$bList = array('1-20', '3-55', '88-99', '40-45');$last = array();$f = array();foreach(array_reverse($aList, true) as $k=>$id){ $last = array('id'=>$id, 'percent'=>$bList[$k], 'other'=>$last);}// 若想去除最底的other=>array(),需要你在foreach中判断一下$result['other'] = $last;
$result = array( 'x' => 'xxx', 'y' => 'yyy',);$aList = array(55,99,77,44);$bList = array('1-20', '3-55', '88-99', '40-45');function listMerge($aList = array(), $bList = array()){ if(count($aList) != count($bList)){ return false; } $newList = array(); if(!empty($aList) && !empty($bList)){ $newList['id'] = $aList[0]; $newList['pcenter'] = $bList[0]; array_shift($aList); array_shift($bList); $newList['other'] = listMerge($aList, $bList); } return $newList; }$result['other'] = listMerge($aList, $bList);echo "";print_r($result);die;
楼上给出了一种方法,这是一种递归的方法。比楼上复杂一些...供参考。同样,想去除最底的other=>array(),需要你在判断一下谢谢..我自己也完成了
$result['other'] = array();
$curPoint = &$result['other'];
for($i = 0; $i < count($aList); $i++){
$resultItem = array();
$resultItem ['id'] = $aList[$i];
$resultItem ['percent'] = $bList[$i];
$curPoint = $resultItem;
if(isset($aList[$i+1])){
$curPoint = &$curPoint['_complex'];
}
}
谢谢...坑爹的需求继续在变,继续给另一需求写算法.睡个觉再管.