>假设我有一个数组
$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值,该过程应继续。
虽然我很确定这是一个家庭作业,而且你真的应该提供自己的代码,至少尝试一下,我觉得这件事很有趣,所以我继续尝试一下。我想我会为他投反对票,我可能确实应得的,但无论如何,这里还是这样。
您需要做的是:
- 遍历数组,
- 确定给你 32 的元素,然后将结果存储在最终数组中。
- 从工作数组的相应元素中减去结果中最后一个元素的值
- 接下来通过删除第一个元素来缩小数组,直到您仍在使用的数组的第一个元素等于最后一个结果返回的最后一个元素。
- 如果您的最后结果<32,请退出。
考虑到这一点,请先尝试自己找到解决方案,而不仅仅是复制粘贴代码? :)
<?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);