drzrzzkh462254 2016-02-11 11:25
浏览 109
已采纳

PHP基于数组长度的循环N次

I have this array :

$products = array('0', '1', '2', '3');

and I want to have this combination :

0
0,1
0,1,2
0,1,2,3 // my code can't show this result
0,1,3 // my code can't show this result
0,2
0,2,3
0,3
1
1,2
1,2,3
1,3
2
2,3
3

and here's my code :

$rows = count($products);
for ($i = 0; $i < $rows; $i++) {

    echo $i . '<br>';

    for ($j = $i + 1; $j < $rows; $j++){
        echo $i . $j . '<br>';

        if (!empty($products[$j+1])) {
            echo $i . $j . $products[$j+1] . '<br>';
        }

    }

}

but, unfortunately I missed 2 results :

0,1,2,3
0,1,3

and I still have doubt about this for loop inside loop, while the number of combination is determined by array length.

how to get that missed combination and perfectly works for different array length?

  • 写回答

2条回答 默认 最新

  • dongshen4129 2016-02-11 11:30
    关注

    Try this

        <?php
            $set = array('0', '1', '2','3');
            $power_set = possible_set($set);
            echo "<pre>";
            print_r($power_set);
            echo "</pre>";
            function possible_set($array) {
                $results = array(array( ));
                foreach ($array as $element)
                    foreach ($results as $inner_element)
                        array_push($results, array_merge(array($element), $inner_element));
    
                unset($results[0]);
                $results = array_values($results);
                return $results;
            }
        ?>
    

    https://eval.in/516963

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Stata 面板数据模型选择
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用