1

I have 2 arrays. 1 with items that should always be used and 1 with optional items. What I want is a list of all possible combinations with these items. The items in the array have to become attributes with a true or false value.

For example, the arrays

$requiredAttr = array('header', 'footer');
$optAttr = array('image');

Should give the following result:

header="false" footer="false"
header="false" footer="false" image="false"
header="false" footer="false" image="true"
header="true" footer="false"
header="true" footer="false" image="false"
header="true" footer="false" image="true"
header="false" footer="true"
header="false" footer="true" image="false"
header="false" footer="true" image="true"
header="true" footer="true"
header="true" footer="true" image="false"
header="true" footer="true" image="true"

Ofcourse this has the work with any number of items in both arrays.

1
  • Thanx for awasome question...
    – sandeep
    Mar 8, 2012 at 11:49

3 Answers 3

0

check this.. change variable name according to your standard.. i print all array for debuging.

http://codepad.org/HK1plx9n

more optimised code

http://codepad.org/pwVOWeRJ

<?php

$requiredAttr = array('header', 'footer');
$boolarr = array('true', 'false');
$optAttr = array('image' );

$larr  = combine_array($requiredAttr , $boolarr , '=');

$a_arr = array_slice($larr , 0 , count($larr)/2);
$b_arr = array_slice($larr , count($larr)/2 , count($larr)/2);


$larr_1    = combine_array($a_arr , $b_arr , ' ');
$larr     = combine_array($optAttr , $boolarr , '=');
array_push($larr , ''); // for optional

$larr_3  = combine_array($larr_1 , $larr , ' ');

function combine_array($first_arr , $second_arr , $separator)
{
    $combine_arr  = array();
    for($i=0;$i<count($first_arr) ; $i++)
    {
    for($j=0;$j<count($second_arr) ; $j++)
    {
        array_push($combine_arr , $first_arr[$i].$separator.$second_arr[$j]);
    } 
    }
    return $combine_arr;
}



print_r($larr_3);



?>
0

You can probably implement this with a binary tree that simply returns all its values. Something like (theoretical only, probably won't work):

function a($bool_arr, $required, $optional)
{
    if (count($bool_arr) < (count($required) + count($optional))
    {
        return array_merge(a(array_merge($bool_arr), array(true), $required, $optional), a(array_merge($bool_arr), array(false), $required, $optional));
    }
}
0

separate all required from the optional attributes and use for each set this gist. When you've build the combinatorics of each set you'll simply copy each combinatorics from the required combinatorics set to this array and append every optional combinatorics optional set to every required combinatorics set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.