Reputation: 798
I'm trying to remove duplicate form foreach
but it doesn't work.
I know I can do this with SQL but I need to use PHP.
My code:
<?php foreach($cities as $city):?>
<a class="btn" href="$city['url'];?>">
<?= $city['city'];?>
</a>
<?php endforeach;?>
Result:
> London
> New York
> Paris
> New York
> Berlin
I tried with array_unique
but it doesn't work too.
<?php foreach(array_unique($cities) as $city):?>
<a class="btn" href="$city['url'];?>">
<?= $city['city'];?>
</a>
<?php endforeach;?>
Where I'm wrong?
edit:
Array (
[0] => Array ( [city] => London [url] => London--UK )
[1] => Array ( [city] => New York [url] => NewYork--USA )
[2] => Array ( [city] => Paris [url] => Paris--France )
[3] => Array ( [city] => New York [url] => NewYork--USA )
[5] => Array ( [city] => Berlin [url] => Berlin--Germany )
)
Upvotes: 1
Views: 1399
Reputation: 723
Try this
<?php
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
?>
Use
$details = array(
0 => array("id"=>"1", "name"=>"Mike", "num"=>"9876543210"),
1 => array("id"=>"2", "name"=>"Carissa", "num"=>"08548596258"),
2 => array("id"=>"1", "name"=>"Mathew", "num"=>"784581254"),
);
$details = unique_multidim_array($details,'id');
Source is a User Contributed Notes in http://php.net/manual/es/function.array-unique.php
Upvotes: 1