假设我有一个数组
$x= ('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
我需要像这样生成一个数组
$newx = (0 => array('A'=>31 , 'B' =>1) , 1 => array('B'=>11 , 'C' =>13 , 'D'=>8) , 2 =>array('D'=>17 , 'E'=>15) , 3=>array('E'=>3,'F'=>10);
现在,在这种情况下,$newx
的每个值必须为= 32
,这就是它的工作方式$x[A] = 31 , $x[B] = 12
所以首先我们必须使总和数量保持为32新数组的索引相同,即
array(0=>array('A'=>31,'B'=>1) , 1=>array('B'=>11) )
对于$ x的每个值,该过程应该继续。
答案 0 :(得分:0)
虽然我很确定这是一项家庭作业,但你真的应该提供自己的代码,至少尝试一下,我发现这件事很有趣所以我继续尝试了。我想我会为他而投票,我可能确实应该得到它,但无论如何都要进行。
您需要做的是:
考虑到这一点,请先尝试自己找一个解决方案,不要只复制粘贴代码吗? :)
<?php
$x = array('A'=>31, 'B'=>12, 'C'=>13, 'D'=>25, 'E'=>18, 'F'=>10);
$result = array();
function calc($toWalk){
// walk through the array until we have gathered enough for 32, return result as an array
$result = array();
foreach($toWalk as $key => $value){
$count = array_sum($result);
if($count >= 32){
// if we have more than 32, subtract the overage from the last array element
$last = array_pop(array_keys($result));
$result[$last] -= ($count - 32);
return $result;
}
$result[$key] = $value;
}
return $result;
}
// logic match first element
$last = 'A';
// loop for as long as we have an array
while(count($x) > 0){
/*
we make sure that the first element matches the last element of the previously found array
so that if the last one went from A -> C we start at C and not at B
*/
$keys = array_keys($x);
if($last == $keys[0]){
// get the sub-array
$partial = calc($x);
// determine the last key used, it's our new starting point
$last = array_pop(array_keys($partial));
$result[] = $partial;
//subtract last (partial) value used from corresponding key in working array
$x[$last] -= $partial[$last];
if(array_sum($partial) < 32) break;
}
/*
reduce the array in size by 1, dropping the first element
should our resulting first element not match the previously returned
$last element then the logic will jump to this place again and
just cut off another element
*/
$x = array_slice($x , 1 );
}
print_r($result);