Split array into unique pairs

前端 未结 6 1406
感动是毒
感动是毒 2021-01-06 02:05

Say i start with a simple array (which could be theoretically of any length):

$ids  = array(1,2,3,4);

What it the best solution for splitti

6条回答
  •  日久生厌
    2021-01-06 02:36

    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]);
      }
    }
    

    See this in action at http://www.ideone.com/9wzvP

提交回复
热议问题