假设我从一个简单的数组开始(理论上可以是任意长度):
$ids = array(1,2,3,4);
将这个数组拆分为一组唯一对的数组的最佳解决方案是什么,例如:
$pair[0] = array(1,2);
$pair[1] = array(1,3);
$pair[2] = array(1,4);
$pair[3] = array(2,3);
$pair[4] = array(2,4);
$pair[5] = array(3,4);
The simplest solution is to use a nested loop and build combinations as you go, although note that the complexity here is O(n2).
$ids = array(1,2,3,4,4);
$combinations = array();
$ids = array_unique($ids); // remove duplicates
$num_ids = count($ids);
for ($i = 0; $i < $num_ids; $i++)
{
for ($j = $i+1; $j < $num_ids; $j++)
{
$combinations[] = array($ids[$i], $ids[$j]);
}
}
请参阅以下网址的实际操作:http://www.ideone.com/9wzvP
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)