简体   繁体   English

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

[英]Php print out value from array only once

well my code is this one and i want if the locationname is the same to be printed only once 好吧,我的代码是这一个,我想如果locationname是相同的只打印一次

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

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

Do it: 这样做:

$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;

EDIT Another way . 编辑另一种方式。 By comment @grebneke 评论@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;

You should instead make use of PHP built-in function array_unique() . 您应该使用PHP内置函数array_unique() Technically this function will only return the unique elements from the array. 从技术上讲,此函数仅返回数组中的唯一元素。

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

I found a solution, I added an id and name field to my array and used 我找到了一个解决方案,我在我的数组中添加了一个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;
}

thank you all 谢谢你们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM