List all combination possible in a php array of boolean value in PHP

為{幸葍}努か 提交于 2019-12-11 11:59:49

问题


I will try to better explain my needs.

I need to generate from scrach, a multidirectional array who contain many array. The inner array must be array containing 7 boolean value. I need to have all the combinaisons possible of 7 boolean values. With 7 cases, it make 128 inner arrays.

Here an example of output I need, for making it easy to understand :

$sequence = array(
    array(true, true, true, true, true, true, true),
    array(true, true, true, true, true, true, false),
    array(true, true, true, true, true, false, false)
);

I need to have all combinaison possible of Boolean value for each 7 array value.

I try to find solution before posting this, but I found nothing.

Thank you for your help

P-S.: Later, I will need to do the same thing, but with 30 boolean values per table instead of 7. So if the solution can be flexible, it's a bonus!

Solution : This is how I've successfully got what I need, with a little modification of the solution I checked.

<?php

$length = 7;

$totalCombos = pow(2, $length);

$sequences = array();

for($x = 0; $x < $totalCombos; $x++) {
    $sequence[$x] = str_split(str_pad(decbin($x), $length, 0, STR_PAD_LEFT));
}

?>

I have add str_split for having an array of individual value.


回答1:


This will do it and it's flexible.

<?php

$length = 7;

$totalCombos = pow(2, $length);

for($x = 0; $x < $totalCombos; $x++) {
    echo str_pad(decbin($x), $length, 0, STR_PAD_LEFT) . PHP_EOL;
}


来源:https://stackoverflow.com/questions/29996895/list-all-combination-possible-in-a-php-array-of-boolean-value-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!