阵列中的OUTPUT Alone 1键

时间:2018-10-17 11:33:44

标签: php regex

如果_from_t的唯一来源,怎么办---选择具有较高ID的_Alone

从数组中删除其他

array (
  0 => 
  array (
    'id' => '8',
    '_from' => '2',
    '_to' => '1',
    'date' => '2018-10-15 15:51:07',
    'message' => 'ccccccxxxxx',
    'read' => '0',
    'feedback' => '0',
    'cnt' => '3',
  ),
  1 => 
  array (
    'id' => '6',
    '_from' => '1',
    '_to' => '2',
    'date' => '2018-10-15 15:47:01',
    'message' => 'zzzzzzz1',
    'read' => '1',
    'feedback' => '0',
    'cnt' => '1',
  ),

1 个答案:

答案 0 :(得分:1)

如果数组较小,则运行复杂度为O(n 2 )的算法不是问题。但是对我来说,更好的是不清楚的,但是算法更快,复杂度等于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