【问题标题】:create another multi dimensional array from an array从数组创建另一个多维数组
【发布时间】:2012-06-09 11:06:57
【问题描述】:

假设我有一个数组

$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
  • 这是家庭作业,对吧?如果是,您应该这样标记它。 :)
  • 亲爱的@HaraldBrinkhof,这不是家庭作业,我被困在这个问题的某些部分,需要一点帮助。
  • 对于我的误判,我深表歉意。 :)

标签: php arrays multidimensional-array


【解决方案1】:

虽然我很确定这是一项家庭作业,但您确实应该提供自己的代码,至少尝试一下,我觉得这很有趣,所以我继续尝试。我想我会因为他而被否决,我可能确实应该得到它,但不管怎样。

你需要做的是:

  1. 循环遍历你的数组,
  2. 确定给出 32 的元素,然后将结果存储到最终数组中。
  3. 从工作数组的相应元素中减去结果中最后一个元素的值
  4. 接下来通过删除第一个元素来缩小您的数组,直到您仍在使用的数组的第一个元素等于您最后一个结果返回的最后一个元素。
  5. 如果你最后的结果

考虑到这一点,请先尝试自己寻找解决方案,不要只是复制粘贴代码? :)

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

【讨论】:

  • @Aman:看到您建议的编辑:array_slice 不会改变关联键,只有数字索引,请阅读dk.php.net/manual/en/function.array-slice.php :)
  • 最后 2 个是可选的,因此它们出现在 [ ] :) 之间 离开长度使其选择从偏移量开始的整个数组,并且 preserve_keys 不适用于此示例,因为它处理位置索引我们在这里使用关联键。
  • 非常正确,只是添加了评论,因为实际上在我真正的问题中,数组有数字索引。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-24
  • 1970-01-01
  • 2019-07-25
  • 2014-09-25
  • 2013-03-21
  • 1970-01-01
相关资源
最近更新 更多