[ create a new paste ] login | about

Link: http://codepad.org/CiukXctS    [ raw code | output | fork ]

PHP, pasted on Nov 6:
<?php
$array = array(array(17,99), 
            array(45, 131),
            array(17,121),
            array(99,77),
            array(45, 51)

      );
$tmp = array();
foreach($array as $value)
{
    // just for claraty, let's set the variables
    $val1 = $value[0];
    $val2 = $value[1];
    $found = false;
    foreach($tmp as &$v)
    {
        // check all existing tmp for one that matches
        if(in_array($val1, $v) OR in_array($val2, $v))
        {
            // this one found a match, add and stop
            $v[] = $val1;
            $v[] = $val2;
            // set the flag
            $found = true;
            break;
        }
    }
    unset($v);

    // check if this set was found  
    if( ! $found)
    {
        // this variable is new, set both
        $tmp[] = array(
                $val1,
                $val2,
                );
    }
}

// go trough it all again to ensure uniqueness
$array = array();
foreach($tmp as $value)
{
    $array[] = array_unique($value); // this will eliminate the duplicates from $val2
}

var_dump($array);


Output:
array(2) {
  [0]=>
  array(4) {
    [0]=>
    int(17)
    [1]=>
    int(99)
    [3]=>
    int(121)
    [5]=>
    int(77)
  }
  [1]=>
  array(3) {
    [0]=>
    int(45)
    [1]=>
    int(131)
    [3]=>
    int(51)
  }
}


Create a new paste based on this one


Comments: