Home  >  Article  >  Backend Development  >  求助

求助

WBOY
WBOYOriginal
2016-06-23 14:05:14785browse

以下代码$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'];
            }
        }

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn