我有这个foreach:
<?php foreach ($manufacturers as $key => $manufacturer) {
if($manufacturer->virtuemart_manufacturercategories_id == 1){
$lang = 'heb'; //Hebrew
} else {
$lang = 'eng'; //English
}
//add to letter list
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
${'html_letters_'.$lang}[] = $letter;
/*
echo '<pre>';
print_r($manufacturer);
echo '</pre>';*/
$link = JROUTE::_('index.php?option=com_virtuemart&view=category&virtuemart_manufacturer_id=' . $manufacturer->virtuemart_manufacturer_id);
${'html_manufacturers_'.$lang} .= '<div class="manufacturer" data-lang="'.$lang.'" data-letter="'.$letter.'"><a href="'.$link.'">';
?>
<?php
if ($manufacturer->images && ($show == 'image' or $show == 'all' )) {
${'html_manufacturers_'.$lang} .= $manufacturer->images[0]->displayMediaThumb('',false);
}
if ($show == 'text' or $show == 'all' ) {
${'html_manufacturers_'.$lang} .= '<div>'.$manufacturer->mf_name.'</div>';
}
${'html_manufacturers_'.$lang} .= '</a>
</div> <!-- /manufacturer -->';
if ($col == $manufacturers_per_row){
$col = 1;
} else {
$col++;
}
}
?>
我如何检查我是否有超过2个相同的字母并取消所有其他字母,但保留一个。
信件的输出是:
AABCHKIUKP
我希望这会是:
ABCHKIUKP
我是怎么做到的?
编辑:我已经更新了所有的foreach代码。问题是,如果我有更多相同的起始字母名称EG:香气,空气循环取第一个字母A并预先他2次,我想只显示一个,如果有甚至10个相同的起始名称。/ p>感谢。
答案 0 :(得分:0)
当我理解你的时候......只需使用数组
<?php
$letters = array();
foreach ($manufacturers as $key => $manufacturer) {
....
$letter = mb_substr($manufacturer->mf_name, 0, 1, 'UTF-8');
$letters[] = $letter;
}
$uni = array_unique($letters)
echo implode('',$uni);
答案 1 :(得分:0)
$s = 'AABCHKIUKP';
$letters = $letters = preg_split('/(?<!^)(?!$)/u', $s); //utf8
$prev_letter = '';
$temp = '';
foreach($letters as $key => $letter) {
if (!($letter === $prev_letter)) {
$temp .= $letter;
}
$prev_letter = $letter;
}
echo $temp;
结果:
ABCHKIUKP
有关将utf8字符串分解为数组的信息,您可以在此处的评论中找到mb_split。
答案 2 :(得分:0)
要剥离仅相同的连续字符,您可以使用此字符:
function stripConsecutiveChars( $string ) {
// creates an array with chars from the string
$charArray = str_split( $string );
// saves the last char thats on the new string
$lastChar = "";
// variable for the new string to return
$returnString = "";
foreach( $charArray as $char ) {
if( $char === $lastChar ) continue;
$lastChar = $char;// save current char
$returnString .= $char;// concat current char to new string
}
return $returnString;
}
$string = "AABCHKIUKP";
echo stripConsecutiveChars( $string );
在您的示例中,您可以尝试这样做:
...
$letter = mb_substr( $manufacturer->mf_name, 0, 1, 'UTF-8' );
$lastLetter = end( ${'html_letters_' . $lang} );//point to last element in array
reset( ${'html_letters_' . $lang} );// reset the pointer
if( $letter === $lastLetter ) {
// i guess you just want to continue?
continue;
}
...
输出:
ABCHKIUKP