我有一个以下结构的多维数组,我想从中删除重复项。例如,对于两个[“城市”的[“金额”]相同,但[“时间”]是相同或不同的,然后我计算这是一个重复的并且想要从数组中删除此节点。

在以下示例中我想从阵列中删除完全节点0,因为城市和金额与节点1相同。它们都是布里斯托尔(布里斯托尔,英国)和373,即使时间不同为17:15和17:16。

如果时间与在这种情况下,那么我将删除稍后的时间。

array(8) {
  [0]=>
  array(3) {
    ["time"]=>
    string(5) "17:16"
    ["city"]=>
    string(33) "Bristol (Bristol, United Kingdom)"
    ["amount"]=>
    int(373)
  }
  [1]=>
  array(3) {
    ["time"]=>
    string(5) "17:15"
    ["city"]=>
    string(33) "Bristol (Bristol, United Kingdom)"
    ["amount"]=>
    int(373)
  }
  [2]=>
  array(3) {
    ["time"]=>
    string(5) "17:16"
    ["city"]=>
    string(37) "Wednesbury (Sandwell, United Kingdom)"
    ["amount"]=>
    int(699)
  }
  [3]=>
  array(3) {
    ["time"]=>
    string(5) "17:16"
    ["city"]=>
    string(45) "Wolverhampton (Wolverhampton, United Kingdom)"
    ["amount"]=>
    int(412)
  }
  [4]=>
  array(3) {
    ["time"]=>
    string(5) "17:15"
    ["city"]=>
    string(33) "Swansea (Swansea, United Kingdom)"
    ["amount"]=>
    int(249)
  }
  [5]=>
  array(3) {
    ["time"]=>
    string(5) "17:16"
    ["city"]=>
    string(39) "Watford (Hertfordshire, United Kingdom)"
    ["amount"]=>
    int(229)
  }
  [6]=>
  array(3) {
    ["time"]=>
    string(5) "17:14"
    ["city"]=>
    string(39) "Nottingham (Nottingham, United Kingdom)"
    ["amount"]=>
    int(139)
  }
  [7]=>
  array(3) {
    ["time"]=>
    string(5) "17:13"
    ["city"]=>
    string(31) "Dartford (Kent, United Kingdom)"
    ["amount"]=>
    int(103)
  }
}
.

有帮助吗?

解决方案

<?php

$data = array(
    array(
        'time' => '17:16',
        'city' => 'Bristol',
        'amount' => 373,
    ),
    array(
        'time' => '18:16',
        'city' => 'Bristol',
        'amount' => 373,
    ),
    array(
        'time' => '18:16',
        'city' => 'Wednesbury',
        'amount' => 699,
    ),
    array(
        'time' => '19:16',
        'city' => 'Wednesbury',
        'amount' => 699,
    ),
);

$tmp = array();
foreach ($data as $row) {
    $city   = $row['city'];
    $amount = $row['amount'];

    if (!isset($tmp[$city][$amount]) 
        || $tmp[$city][$amount]['time'] < $row['time']) {
        $tmp[$city][$amount] = $row;
    }
}

$data = array();

foreach ($tmp as $cities) {
    foreach ($cities as $city) {
        $data[] = $city;
    }
}

var_dump($data);
.

其他提示

试试:

$result = array();
foreach ($array as $place) {
    if (!array_key_exists($place['time'], $result)) {
        $result[$place['time']] = $place;
    }
}
.

创建二维关联数组,其中一个维度被关键在于城市,另一个维数是金额:

$assoc = array();
foreach ($data as $el) {
    $city = $el['city'];
    $amount = $el['amount'];
    if (isset($assoc[$city]) {
        $assoc[$city][$amount] = $el;
    } else {
        $assoc[$city] = array($amount => $el);
    }
}

// Now gather up all the elements back into a single array
$result = array();
foreach ($assoc as $cities)
    foreach ($cities as $city) {
        $result[] = $city;
    }
}
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top