我试图删除重复的表单foreach
,但它不起作用。
我知道我可以用SQL做到这一点,但我需要使用PHP。
我的代码:
<?php foreach($cities as $city):?>
<a class="btn" href="$city['url'];?>">
<?= $city['city'];?>
</a>
<?php endforeach;?>
结果:
> London
> New York
> Paris
> New York
> Berlin
我尝试使用array_unique
,但它也不起作用。
<?php foreach(array_unique($cities) as $city):?>
<a class="btn" href="$city['url'];?>">
<?= $city['city'];?>
</a>
<?php endforeach;?>
我哪里错了?
编辑:
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 )
)
答案 0 :(得分:1)
试试这个
<?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;
}
?>
使用
$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');
中的用户贡献说明