Reputation: 1792
I've been wrapping my head around this for a couple of days...
I have several arrays that need to be sort of merged into a single array. The order in which they merge is of great importance and is simply the order in which they appear in the global array (like the example below):
$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);
Each input array itself consists of several subarrays that are of equal structure; see http://pastebin.com/fQMUjUpB for an example. This pastebin code also includes the desired output. The output array should contain:
context
and id
elements (glued with a plus) joined together with an ampersand (&); e.g: context1+id1&context2+id2
context1+id1&context2+id2&context3+id3
view
and update
elements are calculated by simply multiplying their corresponding values during merge.$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(...)
);
How can this be accomplished when looping over $global
?
I may have expressed myself quite vaguely (it's really hard to explain!), but hopefully it becomes more clear when you take a look at the pastebin code...
Any help would be greatly appreciated!
Upvotes: 0
Views: 63
Reputation: 388
Here's a minimal working code so that you can get the general idea (if you want to improve the code, feel free, there's a lot to do!):
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);
Upvotes: 2