Php只从数组中打印出一次值

时间:2014-01-24 16:57:39

标签: php arrays foreach

我的代码就是这个,我想如果locationname是相同的,只打印一次

$arr1 =$erster[0][$id[0]]['location'];

foreach ($arr1 AS $ref_key => $location2):
print $location2['locationname'] ;
endforeach;

3 个答案:

答案 0 :(得分:1)

做到:

$arr1 =$erster[0][$id[0]]['location'];

$repeats = array();
foreach ($arr1 AS $ref_key => $location2):
   $local_name = $location2['locationname'];

   if (!in_array($local_name,$repeats)){ // checking if $local_name is exists in "showed" array - $repeats
       print $local_name;                // if not - show $local_name             
       $repeats[] = $local_name;         // push  $local_name to "showed" array ( to $repeats)
   }

endforeach;

编辑另一种方式。评论@grebneke

$repeats = array();
foreach ($arr1 AS $ref_key => $location2):
$local_name = $location2['locationname'];

if (!array_key_exists($local_name,$repeats)){  // -//-
    print $local_name;                           
    $repeats[$local_name] = true;
}

endforeach;

答案 1 :(得分:1)

您应该使用PHP内置函数array_unique()。从技术上讲,此函数仅返回数组中的唯一元素。

$arr1 = $erster[0][$id[0]]['location'];
$newarray = array_unique($arr1);
print_r($newarray);

答案 2 :(得分:0)

我找到了一个解决方案,我在我的数组中添加了一个id和name字段并使用了

if($programm_location_id != $erster_programmpunkt[0][$id[0]]['location']['id']){
$programm_location_id = $erster_programmpunkt[0][$id[0]]['location']['id'];
$programm_location_name = $erster_programmpunkt[0][$id[0]]['location']['name'];
$programm_location_html = '<div class="span3">'.$programm_location_name.'</div>';

echo $programm_location_html;
}

谢谢大家