PHP数组输出,带逗号和“;或;

PHP数组输出,带逗号和“;或;,php,arrays,Php,Arrays,我的php输出是一个数组。比如: $array = array('banana', 'mango', 'apple'); 现在,如果输出仅为“香蕉”,那么它将简单地显示出来 Banana 如果输出是'banana'&'mango'或'apple'我想显示的 Banana or Mango 如果输出为全部。。然后显示结果 Banana, Mango or Apple 现在我可以使用下面的代码用逗号显示结果 echo implode(",<br/>", $array); 回波内

我的php输出是一个数组。比如:

$array = array('banana', 'mango', 'apple');
现在,如果输出仅为“香蕉”,那么它将简单地显示出来

Banana
如果输出是'banana'&'mango''apple'我想显示的

Banana or Mango
如果输出为全部。。然后显示结果

Banana, Mango or Apple
现在我可以使用下面的代码用逗号显示结果

echo implode(",<br/>", $array);
回波内爆(,
,$array); 但是如何添加


请帮助。

使用类似的计数和映射

$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;
}
$count=count($u数组);
如果($count>3){
end($array);//将内部指针移动到数组的末尾
$key=key($array);//获取内部指针指向的元素的键
$last=$your_数组[$key];
unset($your_数组[$key]);
echo内爆(“,
,$your_数组)。”或“$last; }
您可以使用以下函数替换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);
试试这个:

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

请尝试以下代码:

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

相同的答案也适用于此答案。差不多,一个复制品。。这是最简单的方法:$str=内爆(',',数组('banana','mango','apple');echo substr_替换($str,数组('or'),strrpos($str,,')),1);谢谢你的回复@Amit Rajput。。这适用于3个或更多阵列列表吗?这是一个非常简单的解决方案,谢谢。:)这是最简单的方法:$str=内爆(',',数组('banana','mango','apple');echo substr_替换($str,数组('or'),strrpos($str,,')),1);
$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;