Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 496
hsatterwhite Avatar asked Jan 03 '11 14:01

hsatterwhite


People also ask

How to select an element from a multidimensional array?

PHP - Multidimensional Arrays 1 For a two-dimensional array you need two indices to select an element 2 For a three-dimensional array you need three indices to select an element More ...

What is a multidimensional array in JavaScript?

A multidimensional array is an array of arrays. To create a two-dimensional array, add each array within its own set of curly braces: myNumbers is now an array with two arrays as its elements. To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array.

How many elements can be stored in a multidimensional array?

Similarly array int x [5] [10] [20] can store total (5*10*20) = 1000 elements. Two – dimensional array is the simplest form of a multidimensional array.

What are the advantages of multidimensional arrays?

To conclude, multidimensional arrays allow us to handle similar and different types of data types. Multidimensional arrays are very powerful to handle large and related data.


2 Answers

Just looking at your particular case, I would recommend using a hash table instead of a 2-dimensional array. If you use your "name" as the key in the hash, each entry would be unique.

Is there a specific need for the multidimensional array?

like image 127
Gobs Avatar answered Sep 27 '22 23:09

Gobs


You can use an associative array.

$temp_array = array();
foreach ($array as &$v) {
    if (!isset($temp_array[$v['name']]))
        $temp_array[$v['name']] =& $v;
}

This creates a temporary array, using $v['name'] as the key. If there is already an element with the same key, it is not added to the temporary array.

You can convert the associative array back to a sequential array, using

$array = array_values($temp_array);

Example code and output: http://codepad.org/zHfbtUrl

like image 22
Thai Avatar answered Sep 27 '22 21:09

Thai