Reputation: 927
I have multidimensional array as follows.
array(
0 => array(
'id' => '6',
'name' => 'Looper',
'language' => 'hindi'),
1 => array(
'id' => '7',
'name' => 'Rush',
'language' => 'hindi'),
2 => array(
'id' => '6',
'name' => 'Looper',
'language' => 'hindi'));
So I would like to remove an array having same values and it should be like as follows.
array(
0 => array(
'id' => '6',
'name' => 'Looper',
'language' => 'hindi'),
1 => array(
'id' => '7',
'name' => 'Rush',
'language' => 'hindi'));
Please help me to get the solution.
Upvotes: 0
Views: 340
Reputation: 479
Pass to variable to hold the keys, check using in_array
function assc_array_filter($array, $id)
{
$keys = array();
foreach($array as $index => $arr)
{
if(in_array($arr[$id], $keys))
{
unset($array[$index]);
}
else
{
$keys[] = $arr[$id];
}
}
return $array;
}
call function as
print_r(assc_array_filter($arr, 'id'));
----UPDATED: switch using array_search
Above code will return the first in array, not the "second set" found on the array, so.. Added a parameter to allow it to update the "first set" that found..
function assc_array_filter($array, $id, $last_updated = false, $strict = false)
{
$keys = array();
foreach($array as $index => $arr)
{
if(($in_index = array_search($arr[$id], $keys, $strict)) !== false )
{
if($last_updated)
{
$array[$in_index] = $arr;
}
unset($array[$index]);
}
else
{
$keys[] = $arr[$id];
}
}
return $array;
}
Call as
print_r(assc_array_filter($arr, 'id', true));
Upvotes: 0
Reputation: 4097
$oldarr = array(
0 => array(
'id' => '6',
'name' => 'Looper',
'language' => 'hindi'),
1 => array(
'id' => '7',
'name' => 'Rush',
'language' => 'hindi'),
2 => array(
'id' => '6',
'name' => 'Looper',
'language' => 'hindi'));
$newarr = array();
foreach( $oldarr as $v ) if( !in_array( $v, $newarr ) ) $newarr[] = $v;
print_r( $newarr );
That will take care of your problem.. as of PHP 4.2, in_array() will take an array as the first parameter. array_unique() will not work for this solution.. from php.net: "Note: Note that array_unique() is not intended to work on multi dimensional arrays."
Upvotes: 0
Reputation: 57322
can use array_unique()
for remove duplicate entry from a single multidimensional array in php
Upvotes: 2
Reputation: 399
ok, maybe you can try with unset(array[2]), this remove an element from an array http://php.net/manual/en/function.unset.php
Upvotes: 0