2016-02-17 22 views
2

我的php输出是一个数组。像:带有逗号和“或”的PHP数组输出

$array = array('banana', 'mango', 'apple'); 

现在如果产量只有'香蕉'然后它会显示简单

Banana 

如果输出为'香蕉' & '芒果''苹果'我想展示像

Banana or Mango 

如果输出为全..然后结果将显示

Banana, Mango or Apple 

现在,我可以使用此代码

echo implode(",<br/>", $array); 

但如何添加显示与逗号结果?

请帮忙。

+5

对[另一个帖子](http://stackoverflow.com/questions/8586141/implode-array-with-and-add-and-before-last-item)的相同答案可以应用于此回答。几乎,一个副本......只是**和**而不是**或**。 – SergeantHacker

+0

这是最容易的方法: $ str = implode(',',array('banana','mango','apple')); (); strrpos($ str,','),1); –

+0

感谢您的支持@Amit Rajput ..是否适用于3个或更多数组列表? –

回答

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; 
+0

这是非常简单的解决方案,并且非常感谢。 :) –

+0

这是最简单的方法: $ str = implode(',',array('banana','mango','apple')); (); strrpos($ str,','),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; 
} 
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); 
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; 

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