删除多维数组中的重复项

时间:2018-10-20 19:07:22

标签: php arrays duplicates

我有一个包含多个相同数据的数组:

array(2) {
  [0]=>
  array(2) {
    ["id"]=>
    string(11) "43000173601"
    ["data"]=>
    array(2) {
      [0]=>
      array(2) {
        ["id"]=>
        string(5) "52874"
        ["name"]=>
        string(3) "x70"
      }
      [1]=>
      array(2) {
        ["id"]=>
        string(5) "52874"
        ["name"]=>
        string(3) "x70"
      }
    }
  }
  [1]=>
  array(2) {
    ["id"]=>
    string(11) "43000173602"
    ["data"]=>
    array(1) {
      [0]=>
      array(2) {
        ["id"]=>
        string(5) "52874"
        ["name"]=>
        string(3) "x70"
      }
    }
  }
}

我尝试使用array_unique()删除这些条目,但收到此错误:

  

数组到字符串的转换

外部数组包含路由ID,某些总线可能具有2条不同的路由,因此在这种情况下,它们可以保留,但是,我只想删除1条路由中的重复项:

[0]=>
  array(2) {
    ["id"]=>
    string(11) "43000173601"
    ["data"]=>
    array(2) {
      [0]=>
      array(2) {
        ["id"]=>
        string(5) "52874"
        ["name"]=>
        string(3) "x70"
      }
      [1]=>
      array(2) {
        ["id"]=>
        string(5) "52874"
        ["name"]=>
        string(3) "x70"
      }
    }

3 个答案:

答案 0 :(得分:1)

代码可以是这样的:

// there I have called two `onchange event functions` due to some different scenario processing.

<input type="file" class="selectImagesHandlerDialog" 
    name="selectImagesHandlerDialog" 
    onclick="this.value=null;" accept="image/x-png,image/gif,image/jpeg" multiple 
    onchange="delegateMultipleFilesSelectionAndOpen(event); disposeMultipleFilesSelections(this);" />


// delegating multiple files select and open
var delegateMultipleFilesSelectionAndOpen = function (evt) {

  if (!evt.target.files) return;

  var selectedPhotos = evt.target.files;
  // some continuous source

};


// explicitly removing file input value memory cache
var disposeMultipleFilesSelections = function () {
  this.val = null;
};

答案 1 :(得分:1)

您可以使用array_column使数组关联。这将删除所有重复项。
然后,Array_values将删除关联,并再次使其成为普通索引数组。
Rsort确保您获得最低的键作为结果数组。

rsort($arr);
$arr = array_values(array_column($arr, Null, "id"));

答案 2 :(得分:1)

我通过以下操作对其进行了修复:

$stripped = [];
foreach($arr as $single) {
    $stripped[] = ['id' => $single['id'], 'data' => array_unique($single['data'])];
}

由于重复项存在于内部数组而不是外部数组中,因此我必须在内部数组上使用array_unique()