如何从PHP中的数组中获取“子数组”?

时间:2018-01-01 20:28:26

标签: php arrays algorithm data-structures sub-array

我正在寻找一种方法:

我有一个数组如:

$numbers = [1, 2, 3, 4, 5];

但是我需要让一个函数接受这个数字并返回 像这样的子数组:

[1,2,3,4];
[1,2,3,5];
[1,2,4,5];
[1,3,4,5];
[2,3,4,5];
[1,2,3];
[1,2,4];
[1,3,5];
[1,2,5];
[1,2];
[2,3];
[1];
[2];

依旧...... 有点像这样, 我不知道如何使算法做到这一点。

谢谢。

1 个答案:

答案 0 :(得分:0)

我想也许你的输出错了。这些价值观对我没有任何意义,不应该是134 234而不是:

[1,3,5];
[1,2,5];

我知道我不应该为其他人编写代码,以防万一有人看到这个问题,并像我一样对这个问题感到奇怪。

$numbers = [1, 2, 3, 4, 5];
for($q = 0; $q<sizeof($numbers)-1; $q++)
{
  for($i = sizeof($numbers)-1; $i>=0; $i--){
    $temp = $numbers[$i];
    for($w = 0; $w<sizeof($numbers); $w++)
    {
      if ($numbers[$w]!=$temp)
         echo $numbers[$w];
    }
echo "<br>";
   }
    array_pop($numbers);
}

使用嵌套循环结构。创建一个temp来存储正在被省略的数组的元素,遍历数组打印不是temp的值(或者如果你真的想要推送到子数组)然后递减temp。接下来,弹出数组的最后一个元素,直到您向后遍历整个数组。

1234
1235
1245
1345
2345
123
124
134
234
12
13
23
1
2