PHP-生成数组中项目的所有组合 [英] PHP - Generate all combinations of items in array

查看:38
本文介绍了PHP-生成数组中项目的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的PHP数组...

I have a PHP array like this...

$myarray = array(
'red', 'yellow', 'green, 'blue'
);

顺序对我来说并不重要,所以我想我想计算的是组合而不是 permutations .我想把这个找回来...

Order does not matter to me so I think I am trying to calculate combinations rather than permutations. I am wanting to get this back...

$finalarray = array(
    'Red', 'Green',
    'Red', 'Yellow',
    'Red', 'Blue',
    'Green', 'Yellow',
    'Green', 'Blue',
    'Yellow', 'Blue'
);

是否有内置的PHP功能可以实现这一目标,或者是否可以通过循环来实现?

Is there a built in PHP feature for achieving this or is there a way to do it with loops?

推荐答案

您当然可以使用置换库,但是必须按字母顺序对每个子数组进行 sort 排序,并使用 array_unique删除重复项().

You can of course with permutation libraries, but that you have to sort every single subarray alphabetically and remove duplicates with array_unique().

或者您可以尝试提高成本效益:

Or you might try to be more cost efficient:

$myarray = array(
'red', 'yellow', 'green', 'blue'
);

$result = [];

while ($item = array_pop($myarray)) {
    foreach($myarray as $couple) {
        $result[] = [$item, $couple];
    }
}

print_r($result);

第一件事是您要在每个步骤中简化源数组,并且每个上下文都应具有其数组副本.这意味着,如果您愿意将机制封装在递归函数中,以生成两个以上的成员数组,则需要防止其内部副本被其自身上下文的 array_pop 以外的其他内容更改.

First thing is you are reducing a source array every step, and every context should have its copy of array. It means, that if you are willing to encapsulate mechanics in recursive function to generate more that two member arrays, you need to prevent their internal copies from being changed by anything else than array_pop of their own context.

对于上面的代码解释,我将一个元素从源数组的顶部弹出,然后迭代幸存的元素来耦合一对.这样,我就不会将红色"与红色"配对,并且不会产生无序的重复项.

For the explanation of code above, I'm popping one element off the top of source array, and than iterate over survived element to couple a pair. This way I wont pair "red" with "red", and I wont produce disordered duplicates.

这篇关于PHP-生成数组中项目的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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