hsatterwhite hsatterwhite - 7 months ago 12
PHP Question

How can you make a multidimensional array unique?

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"
)
)


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?

Thanks in advance!

Answer

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);

Which will look like this:

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"
  }
}