复杂数组合并


Complex array merge

这几天我一直在想。。。

我有几个数组需要合并到一个数组中。它们合并的顺序非常重要,只是它们在全局数组中出现的顺序(如下面的示例):

$input1 = array(
  array(
    'context' => 'aa', 'id' => 1, 'view' => 1, 'update' => 1,
  ),
  array(
    'context' => 'bb', 'id' => 2, 'view' => 0, 'update' => 0,
  )
);
$input2 = array(
  array(
    'context' => 'cc', 'id' => 3, 'view' => 0, 'update' => 1,
  ),
  array(
    'context' => 'dd', 'id' => 4, 'view' => 0, 'update' => 0,
  ),
  array(
    'context' => 'ee', 'id' => 5, 'view' => 1, 'update' => 0,
  )
);
$input3 = array(
  array(
    'context' => 'ff', 'id' => 6, 'view' => 1, 'update' => 1,
  ),
  array(
    'context' => 'gg', 'id' => 7, 'view' => 1, 'update' => 0,
  ),
);
$global = array($input1, $input2, $input3);

每个输入阵列本身由几个结构相同的子阵列组成;看见http://pastebin.com/fQMUjUpB例如。这个pastebin代码还包括所需的输出。输出数组应包含:

  • 单层阵列
  • "合并下一个输入数组"时的树型遍历,即在两个输入数组之间的合并过程中,应该进行子数组的每一个可能的交叉组合
  • 每个a组合的密钥应该被生成为对应的CCD_ 1和CCD_;例如:context1+id1&context2+id2
  • 对于下一次合并,应使用上一个结果数组,以便上面的示例变为context1+id1&context2+id2&context3+id3
  • 通过在合并期间简单地乘以它们的对应值来计算得到的CCD_ 5和CCD_
$output = array(
  'aa+1&cc+3&ff+6' => array('view' => 0, 'update' => 1),
  'aa+1&cc+3&gg+7' => array('view' => 0, 'update' => 0),
  'aa+1&dd+4&ff+6' => array('view' => 0, 'update' => 0),
  'aa+1&dd+4&gg+7' => array(...),
  'aa+1&ee+5&ff+6' => array(...),
  'aa+1&ee+5&gg+7' => array(...),
  'bb+2&cc+3&ff+6' => array(...),
  'bb+2&cc+3&gg+7' => array(...),
  'bb+2&dd+4&ff+6' => array(...),
  'bb+2&dd+4&gg+7' => array(...),
  'bb+2&ee+5&ff+6' => array(...),
  'bb+2&ee+5&gg+7' => array(...)
);

$global上循环时,如何实现这一点?

我可能表达得很模糊(真的很难解释!),但希望当你看一下pastebin代码时,它会变得更清楚。。。

如有任何帮助,我们将不胜感激!

这里有一个最低限度的工作代码,这样你就可以获得大致的想法(如果你想改进代码,请放心,有很多事情要做!):

function generate_output($globalArray, $context = array(), $view = 1, $update = 1, &$output = array()) {
    if(!count($globalArray)) {
        $output[implode('&', $context)] = array('view' => $view, 'update' => $update);
    }
    else {
        foreach(reset($globalArray) as $elt) {
            $newContext = $context;
            $newContext[] = $elt['context'] . '+' . $elt['id'];
            generate_output(array_slice($globalArray, 1), $newContext, $view * $elt['view'], $update * $elt['update'], $output);
        }
    }
    return $output;
}
generate_output($global);