如何使多维数组唯一? [英] How can you make a multidimensional array unique?

查看:24
本文介绍了如何使多维数组唯一?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组设置,如下所示:

I've got a multidimensional array setup like the following:

array(
  [0]=>
  array(
    ["name"]=> "Foo"
    ["slug"]=> "Bar"
  )
  [1]=>
  array(
    ["name"]=> "Foo"
    ["slug"]=> "Bar"
  )
  [2]=>
  array(
    ["name"]=> "Test 1"
    ["slug"]=> "test-1"
  )
  [3]=>
  array(
    ["name"]=> "Test 2"
    ["slug"]=> "test-2"
  )
  [4]=>
  array(
    ["name"]=> "Test 3"
    ["slug"]=> "test-3"
  )
)

在该区域中搜索name"中的重复值并删除它们,以便多维数组中的每个值都是唯一的,最好的方法是什么?

What would be the best way to search through the area for duplicates values in "name" and remove them, so that each value in the multidimensional array is unique?

提前致谢!

推荐答案

既然每个人都给出了替代方案,这里是手头问题的解决方案.有时我们必须使用我们拥有的数据,而不是按照我们喜欢的方式重新排列它.话虽如此,这将从数组中删除所有重复的后续条目.

Since everyone given alternatives, here's a solution to the problem at-hand. Sometimes we have to work with the data we have, not re-arrange it the way we like it. That being said, this will remove all sub-sequent entries from the array that are duplicates.

$array = Array(
  Array(
    'name'  => 'Test 3',
    'slug'  => 'test-3'
  ),
  Array(
    'name'  => 'Foo',
    'slug'  => 'Bar'
  ),
  Array(
    'name'  => 'Foo',
    'slug'  => 'Bar'
  ),
  Array(
    'name'  => 'Test 1',
    'slug'  => 'test-1'
  ),
  Array(
    'name'  => 'Test 2',
    'slug'  => 'test-2'
  ),
  Array(
    'name'  => 'Test 3',
    'slug'  => 'test-3'
  ),
);
var_dump($array);

for ($e = 0; $e < count($array); $e++)
{
  $duplicate = null;
  for ($ee = $e+1; $ee < count($array); $ee++)
  {
    if (strcmp($array[$ee]['name'],$array[$e]['name']) === 0)
    {
      $duplicate = $ee;
      break;
    }
  }
  if (!is_null($duplicate))
    array_splice($array,$duplicate,1);
}
var_dump($array);

看起来像这样:

array(6) {
  [0]=>
  array(2) {
    ["name"]=>
    string(6) "Test 3"
    ["slug"]=>
    string(6) "test-3"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(3) "Foo"
    ["slug"]=>
    string(3) "Bar"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(3) "Foo"
    ["slug"]=>
    string(3) "Bar"
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(6) "Test 1"
    ["slug"]=>
    string(6) "test-1"
  }
  [4]=>
  array(2) {
    ["name"]=>
    string(6) "Test 2"
    ["slug"]=>
    string(6) "test-2"
  }
  [5]=>
  array(2) {
    ["name"]=>
    string(6) "Test 3"
    ["slug"]=>
    string(6) "test-3"
  }
}
array(4) {
  [0]=>
  array(2) {
    ["name"]=>
    string(6) "Test 3"
    ["slug"]=>
    string(6) "test-3"
  }
  [1]=>
  array(2) {
    ["name"]=>
    string(3) "Foo"
    ["slug"]=>
    string(3) "Bar"
  }
  [2]=>
  array(2) {
    ["name"]=>
    string(6) "Test 1"
    ["slug"]=>
    string(6) "test-1"
  }
  [3]=>
  array(2) {
    ["name"]=>
    string(6) "Test 2"
    ["slug"]=>
    string(6) "test-2"
  }
}

这篇关于如何使多维数组唯一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆