我的php输出是一个数组。喜欢:
$array = array('banana', 'mango', 'apple');
现在如果输出只是'香蕉',那么它只会显示
Banana
如果输出'香蕉'& '芒果'或'apple'我希望展示
Banana or Mango
如果输出全部是..那么结果将显示
Banana, Mango or Apple
现在我可以使用此代码以逗号显示结果
echo implode(",<br/>", $array);
但如何添加或 ??
请帮忙。
答案 0 :(得分:2)
试试这个:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
答案 1 :(得分:0)
使用计数和地图,如
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
答案 2 :(得分:0)
你可以用这个函数替换php中最后一次出现的字符串:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
答案 3 :(得分:0)
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
答案 4 :(得分:0)
请尝试以下代码:
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;