How to find every possible combination of arrays in PHP

后端 未结 2 872
一向
一向 2020-12-20 08:21
$data = array(
\'a\' => array(\'a1\', \'a2\', \'a3\'),
\'b\' => array(\'b1\', \'b2\', \'b3\', \'b4\'),
\'c\' => array(\'c1\', \'c2\', \'c3\', \'c4\', \'c5\'         


        
相关标签:
2条回答
  • 2020-12-20 09:06

    If you want to print them all out, just use loops:

    foreach($data['a'] as $k1 =>$v1){
        $output[]=$v1;
        foreach($data['b'] as $k2 => $v2){
            $output[]=$v2;
            $output[]=$v1."-".$v2;
            foreach($data['c'] as $k3 => $v3){
                $output[]=$v3;
                $output[]=$v1."-".$v2."-".$v3;
            }
        }
    } 
    

    http://www.webdeveloper.com/forum/showthread.php?t=168409

    Google is awesome that way...

    If you want to see how many possibilities there are, multiply them:

    $count1=1;
    $count2=1;
    for each $data as $item{
    $count2*=count($item);
    }
    
    0 讨论(0)
  • 2020-12-20 09:08

    Apparently you want to build the cartesian product of several arrays, i.e. every element combined with each other element.

    In addition, you want to have result tuples that omit one or more of those arrays which, for the sake of simplicity, I would model as having a null element in each of those arrays:

    $result = array(array()); // We need to start with one element already, because thats the identity element of the cartesian product
    foreach ($data as $arr)
    {
        array_push($arr,null); // Add a null element to the array to get tuples with less than all arrays
    
        // This is the cartesian product:
        $new_result = array();
        foreach ($result as $old_element)
            foreach ($arr as $el)
                $new_result []= array_merge($old_element,array($el));
        $result = $new_result;
    }
    

    Note that for your result line a1 b3 c2 this code gives you array('a1','b3','c2') and for your result line b4 c3 this code gives you array('b4','c3',null).

    0 讨论(0)
提交回复
热议问题