复杂数组合并

时间:2014-11-08 20:33:44

标签: php arrays

我已经把头缠了好几天......

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

$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代码还包括所需的输出。 输出数组应包含:

  • 单级数组
  • 在"合并下一个输入数组"的一个树状的直通,即。在两个输入数组合并期间,应该在子数组的每个可能的交叉组合中进行。
  • 每个组合的关键字应该生成为相应的contextid元素(用加号粘合)的连接字符串,用和号(&)连接在一起;例如:context1+id1&context2+id2
  • 对于下一个合并,应使用上一个结果数组,以便从上面的示例变为 context1+id1&context2+id2&context3+id3
  • 生成的viewupdate元素只需在合并期间乘以相应的值即可计算出来。
$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代码时会更清楚......

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

这是一个最小的工作代码,这样你就可以得到一般的想法(如果你想改进代码,感觉自由,还有很多工作要做!):

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);
相关问题