>  기사  >  백엔드 개발  >  求助

求助

WBOY
WBOY원래의
2016-06-23 14:05:14786검색

以下代码$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 "<pre class="brush:php;toolbar:false">";print_r($result);die;

楼上给出了一种方法,这是一种递归的方法。比楼上复杂一些...供参考。同样,想去除最底的other=>array(),需要你在判断一下

谢谢..我自己也完成了

        $result['other'] = array();
        $curPoint = &$result['other'];
        for($i = 0; $i              $resultItem = array();
            $resultItem ['id'] = $aList[$i];
            $resultItem ['percent'] = $bList[$i];

            $curPoint = $resultItem;
            if(isset($aList[$i+1])){
                $curPoint = &$curPoint['_complex'];
            }
        }

谢谢...坑爹的需求继续在变,继续给另一需求写算法.睡个觉再管.

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.