dtlc84438 2019-03-05 15:04
浏览 93
已采纳

PHP中布尔值的所有组合

Related to Generating all the combinations of a set of boolean variables in Haskell and various other questions of the type.

I have a bunch of toggle switches in a database and want to get a list of all possible settings. The number of switches can change, specifically, users can add or remove.

I can get them into an array like

$switches = array('aaa', 'bbb', 'ccc');

and I would like to generate all possibilities, i.e. something like:

$states = array(
array('aaa' => false, 'bbb' => false, 'ccc' => false),
array('aaa' => false, 'bbb' => false, 'ccc' => true),
array('aaa' => false, 'bbb' => true, 'ccc' => false),
array('aaa' => false, 'bbb' => true, 'ccc' => true),
...
);

I don't particularily care in which order the result set is.

What's an elegant way to generate that?

  • 写回答

2条回答 默认 最新

  • douketangyouzh5219 2019-03-05 15:14
    关注

    Dunno if it's elegant, but for example use array_reduce with a callback:

    $a = ['a', 'b', 'c'];
    $states = array_reduce($a, function ($t, $v) {
        $newt = [];
        if (empty($t)) {
            $newt = [
                [$v => false],
                [$v => true],
            ];
        } else {
            foreach ($t as $item) {
                $newt[] = array_merge($item, [$v => false]);
                $newt[] = array_merge($item, [$v => true]);
            }
        }
    
        return $newt;
    }, []);
    var_dump($states);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效