如何找到在PHP数组的每一个可能的组合 [英] How to find every possible combination of arrays in PHP

查看:113
本文介绍了如何找到在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...

感谢

推荐答案

显然,你想建立几个阵列的笛卡尔积,即每一个元素相互结合元素

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:

$result = array(array()); // We need to start with one element already, because thats the identity element of the cartesian product
foreach ($data as $arr)
{
    array_push($arr,null); // Add a null element to the array to get tuples with less than all arrays

    // This is the cartesian product:
    $new_result = array();
    foreach ($result as $old_element)
        foreach ($arr as $el)
            $new_result []= array_merge($old_element,array($el));
    $result = $new_result;
}

请注意,你的结果行 A1 B3 C2 这code给你阵列(A1,B3,C2 ')和你的结果行 B4 C3 这code给你阵列('B4','C3 ',NULL)

Note that for your result line a1 b3 c2 this code gives you array('a1','b3','c2') and for your result line b4 c3 this code gives you array('b4','c3',null).

这篇关于如何找到在PHP数组的每一个可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆