[Solved] OUTPUT Alone 1 key from the array


If you have small arrays, It is not a problem to run the algorithm with complexity O(n2). But for me better is less clear, but faster algorithm with complexity equals to O(2n)

$array = array(
    array(
        'id'         => 12,
        '_from'      => 1,
        '_to'        => 2
    ),
    array(
        'id'         => 13,
        '_from'      => 4,
        '_to'        => 2
    ),
    array(
        'id'         => 14,
        '_from'      => 2,
        '_to'        => 1
    ),
);
$newArray = [];
foreach ($array as $item) {
    $uniqueRecordKey = $item['_from'].'-'.$item['_to'];
    $oppositeRecordKey = $item['_to'].'-'.$item['_from'];

    //If exists record from the opposite and new ID is greater than previous put
    if (isset($newArray[$oppositeRecordKey])) {
        $newArray[$oppositeRecordKey] = $item;
        continue; //Do not append to the end
    }

    $newArray[$uniqueRecordKey] = $item;
}

var_dump($newArray);

https://3v4l.org/0oL2d

solved OUTPUT Alone 1 key from the array