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!
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 ...
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.
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.
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.
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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With