从数组创建另一个多维数组

时间:2012-06-09 11:06:57

标签: php arrays multidimensional-array

假设我有一个数组

$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的每个值,该过程应该继续。

1 个答案:

答案 0 :(得分:0)

虽然我很确定这是一项家庭作业,但你真的应该提供自己的代码,至少尝试一下,我发现这件事很有趣所以我继续尝试了。我想我会为他而投票,我可能确实应该得到它,但无论如何都要进行。

您需要做的是:

  1. 遍历您的阵列,
  2. 确定为您提供32的元素,然后将结果存储在最终数组中。
  3. 从工作数组的相应元素
  4. 中减去结果中最后一个元素的值
  5. 通过删除第一个元素来缩小数组,直到您仍在使用的数组的第一个元素等于上次返回结果的最后一个元素。
  6. 如果你的上一个结果< 32,退出。
  7. 考虑到这一点,请先尝试自己找一个解决方案,不要只复制粘贴代码吗? :)

    <?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);