note 91134 modified in function.array-unique by danbrown
| From: | danbrown@php.net | Date: | Wed, 27 May 2009 01:33:26 +0000 |
| Subject: | note 91134 modified in function.array-unique by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-156039@lists.php.net to get a copy of this message | ||
One way to use array_unique() to handle the multidimensional array issue is to use an md5 hash of
the serialized array as the key. I've seen some solutions listed here that stored the
serialized string, but that requires unserialization, and moving data back and forth between two
states for little reason is just a bad idea. Instead, you could try this method:
<?php
$values = array();
foreach($data as $d) {
$values[md5(serialize($d))] = $d;
}
sort($values);
?>
This will serialize and hash the value, and store the value with the hash as they key. This will
ensure that each piece is only stored once, as the second attempt to store will just overwrite the
first attempt with identical data.
The sort() at the end is a bit unnecessary, but I had to use it on my project, because the function
I was passing the array to couldn't handle keys that weren't valid XML node names (and
some md5 hash strings will start with numbers, which is invalid for XML).
--was--
One way to use array_unique() to handle the multidimensional array issue is to use an md5 hash of
the serialized array as the key. I've seen some solutions listed here that stored the
serialized string, but that requires unserialization, and moving data back and forth between two
states for little reason is just a bad idea. Instead, you could try this method:
<code>
$values = array();
foreach($data as $d) {
$values[md5(serialize($d))] = $d;
}
sort($values);
</code>
This will serialize and hash the value, and store the value with the hash as they key. This will
ensure that each piece is only stored once, as the second attempt to store will just overwrite the
first attempt with identical data.
The sort() at the end is a bit unnecessary, but I had to use it on my project, because the function
I was passing the array to couldn't handle keys that weren't valid XML node names (and
some md5 hash strings will start with numbers, which is invalid for XML).
http://php.net/manual/en/function.array-unique.php