2014-11-08 89 views
0

我一直包裹着我的頭幾天...複雜的陣列合併

我有幾個數組需要合併成一個單一的數組。在它們合併的順序是非常重要的並且是簡單地在它們出現的全局陣列中(如下面的實例)的順序:

$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元素(用一個加號粘合)的連接字符串, &符號(&); e.g: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時可能?

我可能已經相當模糊(這真的很難解釋!)表達自己,但希望它當你在引擎收錄代碼看一看變得更加清晰......

任何幫助將不勝感激!

+0

你永遠不會有超過將3個數組輸入到$ global數組中? – Maxime 2014-11-08 20:39:19

+0

您使用哪種算法在輸出數組中獲取該索引(如'aa + 1&cc + 3&ff + 6')? – 2014-11-08 20:41:08

+0

@Maxime $ global中輸入數組的數量是變化的 – Propaganistas 2014-11-08 20:46:39

回答

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); 
+0

完成。我對你的答案做了一些小的修改,以進一步推廣它。 – Propaganistas 2014-11-09 10:26:14

+0

謝謝!確實,使用全局變量非常難看:) – Maxime 2014-11-09 10:27:43

+0

另一個審查正在進行中;而不是'$ globalArray [0]'我建議使用'reset($ globalArray)'概括用例。 – Propaganistas 2014-11-09 10:37:27