如何在 PHP 中找到数组的所有可能组合
$data = array(
'a' => array('a1', 'a2', 'a3'),
'b' => array('b1', 'b2', 'b3', 'b4'),
'c' => array('c1', 'c2', 'c3', 'c4', 'c5'));
得到
a1
a2
a3
b1
b2
b3
b4
c1
c2
c3
c4
c5
a1 b1
a1 b2
a1 b3
a1 b4
a1 c1
a1 c2
a1 c3
a1 c4
a1 c5
b1 c1
b1 c2
b1 c3
b1 c4
b1 c5
b2 c1
b2 c2
b2 c3
b2 c4
b2 c5
b3 c1
b3 c2
b3 c3
b3 c4
b3 c5
b4 c1
b4 c2
b4 c3
b4 c4
b4 c5
a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b1 c4
a1 b1 c5
a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b2 c4
a1 b2 c5
a1 b3 c1
a1 b3 c2
a1 b3 c3
a1 b3 c4
a1 b3 c5
a1 b4 c1
a1 b4 c2
a1 b4 c3
a1 b4 c4
a1 b4 c5
etc...
谢谢
$data = array(
'a' => array('a1', 'a2', 'a3'),
'b' => array('b1', 'b2', 'b3', 'b4'),
'c' => array('c1', 'c2', 'c3', 'c4', 'c5'));
to get
a1
a2
a3
b1
b2
b3
b4
c1
c2
c3
c4
c5
a1 b1
a1 b2
a1 b3
a1 b4
a1 c1
a1 c2
a1 c3
a1 c4
a1 c5
b1 c1
b1 c2
b1 c3
b1 c4
b1 c5
b2 c1
b2 c2
b2 c3
b2 c4
b2 c5
b3 c1
b3 c2
b3 c3
b3 c4
b3 c5
b4 c1
b4 c2
b4 c3
b4 c4
b4 c5
a1 b1 c1
a1 b1 c2
a1 b1 c3
a1 b1 c4
a1 b1 c5
a1 b2 c1
a1 b2 c2
a1 b2 c3
a1 b2 c4
a1 b2 c5
a1 b3 c1
a1 b3 c2
a1 b3 c3
a1 b3 c4
a1 b3 c5
a1 b4 c1
a1 b4 c2
a1 b4 c3
a1 b4 c4
a1 b4 c5
etc...
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
显然,您想要构建多个数组的笛卡尔积,即每个元素与其他元素相结合。
此外,您希望结果元组省略一个或多个数组,为了简单起见,我将其建模为每个数组中都有一个
null
元素:请注意,对于您的结果行
a1 b3 c2
此代码为您提供array('a1','b3','c2')
以及结果行b4 c3
此代码为您提供array('b4','c3',null)
。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:Note that for your result line
a1 b3 c2
this code gives youarray('a1','b3','c2')
and for your result lineb4 c3
this code gives youarray('b4','c3',null)
.如果您想将它们全部打印出来,只需使用循环:
http://www.webdeveloper.com/forum/showthread.php?t=168409" rel="nofollow">http://www. webdeveloper.com/forum/showthread.php?t=168409
Google 在这方面非常棒...
如果您想查看有多少种可能性,请将它们相乘:
If you want to print them all out, just use loops:
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: