Reputation: 4886
Simple question have following code but won't work
//Enter your code here, enjoy!
$correo[] = array('valor'=>'[email protected]','registro'=>'23');
$correo[] = array('valor'=>'[email protected]','registro'=>'24');
$correo[] = array('valor'=>'[email protected]','registro'=>'26');
function arrayUnique($myArray){
if(!is_array($myArray))
return $myArray;
foreach ($myArray as &$myvalue){
$myvalue=serialize($myvalue);
}
$myArray=array_unique($myArray);
foreach ($myArray as &$myvalue){
$myvalue=unserialize($myvalue);
}
return $myArray;
}
$arr= arrayUnique($correo);
var_dump($arr);
What I am trying to do is remove those row which has repetitive valor
key for example the result of above array should be
Array (
[0] => Array (
[valor] => '[email protected]'
[registro] => 24
)
)
Upvotes: 0
Views: 40
Reputation: 16997
You may try like this, since you said any one of registro
should be considered.
[akshay@localhost tmp]$ cat test.php
<?php
$array = array(
array('valor'=>'[email protected]','registro'=>'23'),
array('valor'=>'[email protected]','registro'=>'24'),
array('valor'=>'[email protected]','registro'=>'26')
);
function remove_dup($array, $key)
{
foreach( $array as $v )
{
if(! isset($out[ $v[$key] ] ) )
$out[$v[$key]] = $v;
}
return array_values($out);
}
// Input
print_r( $array );
// Output
print_r( remove_dup($array,'valor') );
?>
Output
[akshay@localhost tmp]$ php test.php
Array
(
[0] => Array
(
[valor] => [email protected]
[registro] => 23
)
[1] => Array
(
[valor] => [email protected]
[registro] => 24
)
[2] => Array
(
[valor] => [email protected]
[registro] => 26
)
)
Array
(
[0] => Array
(
[valor] => [email protected]
[registro] => 23
)
)
Upvotes: 1
Reputation: 866
You can do like this...
$correo[] = array('valor'=>'[email protected]','registro'=>'23');
$correo[] = array('valor'=>'[email protected]','registro'=>'24');
$correo[] = array('valor'=>'[email protected]','registro'=>'26');
function arrayUnique($myArray, $uniqueKeyName)
{
// Unique Array for return
$myReturnArray = array();
// Array with the md5 hashes
$arrayHashes = array();
foreach($myArray as $key => $item) {
$hash = md5(serialize($item[$uniqueKeyName]));
if (!isset($arrayHashes[$hash])) {
$arrayHashes[$hash] = $hash;
$myReturnArray[] = $item;
}
}
return $myReturnArray;
}
$arr= arrayUnique($correo, 'valor');
echo "<pre>";
print_r($arr);
echo "</pre>";
Upvotes: 1
Reputation: 31739
You can define the function like -
function arrayUnique($myArray){
if(!is_array($myArray))
return $myArray;
$temp = array();
foreach ($myArray as $myvalue){
$temp[$myvalue['valor']] = $myvalue;
}
return $temp;
}
Store the array with valor
as key. It will store only the last one.
Upvotes: 0