Home » » Remove duplicates from multidimensional array

Remove duplicates from multidimensional array

Written By Unknown on Jumat, 13 Juli 2012 | 23.11

As we know array_unique() removes duplicate values from an array. but array_unique() is not intended to work on multi dimensional arrays. So what to do when it comes to multi dimensional array.

We have to serialize the array with serialize() then run the array_unique() function. Serialization is useful for storing or passing PHP values around without losing their type and structure.

We use unserialize() to make the serialized string into a PHP value again. array_map() will be a handy function in this case.

You can read more about this useful function here.

Using all above four functions we get a little but useful function to remove duplicates from multi dimensional array as follows.

    function multi_array_unique($src){
$output = array_map("unserialize",
array_unique(array_map("serialize", $src)));
return $output;
}

//Call function

$src=array( array("apple","banana"),
array("banana","guava"),
array("apple","banana"),
array("banana","guava")
);

$out=multi_array_unique($src);

Share this article :

Posting Komentar

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger