Split array into unique pairs

前端 未结 6 1369
感动是毒
感动是毒 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

    0 讨论(0)
  • 2021-01-06 02:41

    $pair = array_chunk($ids, 2);

    http://www.php.net/manual/en/function.array-chunk.php

    0 讨论(0)
  • 2021-01-06 02:43

    Sweet solution, Nev Stokes! I changed the 'while' statement to avoid the loop from breaking when one of the values is 0:

    $ids  = array(0, 1, 2, 3, 4);
    $out = array();
    
    while ( !is_null( $item = array_shift($ids) )  ) {
        foreach ($ids as $key=>$value) {
            $out[] = array($item, $value);
        }
    
    }
    
    0 讨论(0)
  • 2021-01-06 02:49

    Fixed from my initial jump-the-gun suggestion of array_chunk()

    Try this instead:

    $ids  = array(1, 2, 3, 4);
    $out = array();
    
    while ($item = array_shift($ids)) {
        foreach ($ids as $key=>$value) {
            $out[] = array($item, $value);
        }
    }
    
    0 讨论(0)
  • 2021-01-06 02:54

    Probably not the best solution

    $ids  = array(1,2,3,4);
    
    $pairs = array();
    foreach($ids as $key => $data){
        foreach($ids as $subkey => $subdata){
            if( $subkey != $key){
                if(!in_array(array($subdata, $data) , $pairs) ){
                    $pairs[] = array($data, $subdata);
                }
            }
        }
    }
    

    Anyway it works

    0 讨论(0)
  • 2021-01-06 02:55
    $ids  = array(1,2,3,4);
    $result=array();
    foreach($ids as $value_1)
    {
      foreach($ids as $value_2)
      {
         if($value_1 !=$value_2)
         {
           $result[]=array($value_1,$value_2);
         }
       }
    }
    echo "<pre>";
    print_r($result);
    
    0 讨论(0)
提交回复
热议问题