Jump to content

[SOLVED] Dynamic recursive/nested foreach??


eviltwinkie

Recommended Posts

Array

(

    [P1] => Array

        (

            0 => A

            1 => B

            2 => C

        )

 

    [P2] => Array

        (

            0 => D

            1 => E

            2 => F

        )

 

    [P3] => Array

        (

            0 => G

        )

 

    [P4] => Array

        (

            0 => H

            1 => I

        )

)

 

foreach ($arrayin[P1] as $value1) {

foreach ($arrayin[P2] as $value2) {

foreach ($arrayin[P3] as $value3) {

foreach ($arrayin[P4] as $value4) {

$arrayout[] = "$value1$value2$value3$value4";

}

}

}

}

 

$arrayout has all the proper possible permutations of the above arrays...no problem there...here's where it gets tricky...

 

If I want to have P5 or P6...etc...how do you create a function or chunk of code such that you can...

 

count(array) and nest each foreach such that you get the same results without having to statically write a case for each senario?

 

Thanks!

Link to comment
Share on other sites

What you are trying to do really does not make any sense at all, at least with how you are going about doing it.

 

$num = count($arrayin);

$i=0;
while ($i < $num) {
       $i++;
       $string .= $arrayin['P'.$i];
}
$arrayout[] = $string;

 

Try that out.

Link to comment
Share on other sites

try

<?php
$arrayin=Array
(
    'P1' => Array
        (
            0 => 'A',
            1 => 'B',
            2 => 'C'
        ),

    'P2' => Array
        (
            0 => 'D',
            1 => 'E',
            2 => 'F',
        ),

    'P3' => Array
        (
            0 => 'G'
        ),

    'P4' => Array
        (
            0 => 'H',
            1 => 'I'
        )
);

function permut($arr){
if (count($arr) == 0) return array('');
$key = array_keys($arr);
$a1 = $arr[$key[0]];
unset($arr[$key[0]]);
$out=array();
$tmp = permut($arr);
foreach ($a1 as $val){
	foreach ($tmp as $val2) $out[] = $val.$val2;
}
return $out;
}
$b = permut($arrayin);
print_r($b);

?>

Link to comment
Share on other sites

What you are trying to do really does not make any sense at all, at least with how you are going about doing it.

 

$num = count($arrayin);

$i=0;
while ($i < $num) {
       $i++;
       $string .= $arrayin['P'.$i];
}
$arrayout[] = $string;

 

Try that out.

 

Not really what I am looking for. I am trying to calculate all the possible permutations for all the values in the arrays. For example...

 

ADGH

ADGI

AEGH

AEGI

AFGH

AFGI

etc

etc

 

Do you know of a better way?

Link to comment
Share on other sites

try

function permut($arr){
if (count($arr) == 0) return array('');
$key = array_keys($arr);
$a1 = $arr[$key[0]];
unset($arr[$key[0]]);
$out=array();
$tmp = permut($arr);
foreach ($a1 as $val){
	foreach ($tmp as $val2) $out[] = $val.$val2;
}
return $out;
}
$b = permut($arrayin);
print_r($b);

?>

 

Thanks...works like a charm! +2 points!! ;)

 

Link to comment
Share on other sites

If I want to have P5 or P6...etc...how do you create a function or chunk of code such that you can...

 

count(array) and nest each foreach such that you get the same results without having to statically write a case for each senario?

 

it's pretty simple, you just create a function and call upon that function inside itself. something like this:

<?php
        function foo($array){
                        if(!isset($values) || empty($values)){ $values = array(); }
                        foreach($array as $key => $val){
                                if(is_array($val)){
                                        foo($val);
                                }else{
                                        $values[] = $val;
                                }
                        }
                        return $values;
                }

        function bar($array){
                        $total = count($array);
                        $perm = 1;
                        for($i = $total; $i < 0; $i--){
                                $perm *= $i;
                        }
                        return $perm;
                }

        foo($array_in);
        bar($values);
?>

 

i think that's what you want. that should give you the number of combinations possible. it won't print all the combinations tho. wasn't sure that's what you wanted.

Link to comment
Share on other sites

Why does it have to have a purpose? I'll bet the OP is just trying to do different things as a method of discovery and learning.

 

Ken

 

well it doesn't have to, but knowing how the function will be deployed always helps me get a good idea of how to code it. also, because many people leave out bits and pieces of important information in their posts when they're looking for help. and you help them with the parameters they've listed, but then you find out that there's a whole other section to the function, and you wouldn't have wasted time coding the original function if you had all of the information to begin with.

Link to comment
Share on other sites

I started off just trying to figure out how best to perform a nested foreach problem...I already had a static solution, but it simply was not elegant. I always try to make everything as dynamic as possible. So while originally a self-learning thing...I actually implemented the code snippent and it works very well which has now got me to thinking about growing it more.

 

I included all the information that was required at the time and got some great help. How to calculate all the permutations using different tables as listed above. I am now attempting to modify the code to ALSO filter out certain values.

 

Example...Using the same array...I want to compute all the valid permutations except for "B"...I want to "skip" all possible combinations for "E" and "F" but still calculate all the valid ones using "D".

 

Array

(

    [P1] => Array

        (

            0 => A

            1 => B

            2 => C

        )

 

    [P2] => Array

        (

            0 => D

            1 => E

            2 => F

        )

 

    [P3] => Array

        (

            0 => G

        )

 

    [P4] => Array

        (

            0 => H

            1 => I

        )

)

 

Why you ask? First because I think I could actually use this in my current code to further simply things...and secondly...because its a challenge and I want to know...reminds me...should I mark the topic as solved as if I wanted help on this second part would constitute a new thread? or should it just be left as is? Thanks!

 

 

Link to comment
Share on other sites

try

<?php
$arrayin=Array
(
    'P1' => Array('A', 'B', 'C'),
    'P2' => Array('D', 'E', 'F'),
    'P3' => Array('G'),
    'P4' => Array('H', 'I')
);
$skip = array('B','D','E');

function permut($arr, $skip = array()){
if (count($arr) == 0) return array('');
$key = array_keys($arr);
$a1 = $arr[$key[0]];
unset($arr[$key[0]]);
if (!is_array($a1) or count($a1) == 0) $a1 = array('');
$out=array();
$tmp = permut($arr,$skip);
foreach ($a1 as $val){
	if (!in_array($val,$skip)) foreach ($tmp as $val2) $out[] = $val.$val2;
}
return $out;
}

$b = permut($arrayin);
print_r($b);
$b = permut($arrayin,$skip);
print_r($b);

?>

or

<?php
$arrayin=Array
(
    'P1' => Array('A', 'B', 'C'),
    'P2' => Array('D', 'E', 'F'),
    'P3' => Array('G'),
    'P4' => Array('H', 'I')
);
$skip = array('P1' => array('B'),'P2' => array('D','E'));

function permut($arr, $skip = array()){
if (count($arr) == 0) return array('');
$key = array_keys($arr);
$a1 = $arr[$key[0]];
unset($arr[$key[0]]);
if (!is_array($a1) or count($a1) == 0) $a1 = array('');
$out=array();
$tmp = permut($arr,$skip);
$s = array_key_exists($key[0],$skip) ? $skip[$key[0]] : array();
foreach ($a1 as $val){
	if (!in_array($val,$s)) foreach ($tmp as $val2) $out[] = $val.$val2;
}
return $out;
}

$b = permut($arrayin);
print_r($b);
$b = permut($arrayin,$skip);
print_r($b);

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.