$array = new array('mike will made-it', 'miley cyrus', 'wiz khalifa', 'juicy j');
这是我到目前为止所做的,但我认为这是一种简单而快捷的方法。
public function get_artist() {
$artists = 'Mike WiLL Made-It,Miley Cyrus,Wiz Khalifa, Juicy J';
$artist_array = explode(',', $artists);
if(sizeof($artist_array) == 1)
return $artist_array[0];
else if(sizeof($artist_array) == 2) {
return $artist_array[0] . ' ft. ' . $artist_array[1];
} else if(sizeof($artist_array) > 2) {
//echo sizeof($artist_array);
$ar = '';
foreach($artist_array as $k=>$v) {
if($k == 0)
$v .= ' ft. ';
else if($k > 0 && ($k < (sizeof($artist_array) - 2)))
$v .= ', ';
else if($k == (sizeof($artist_array) - 1))
$v = ' and ' . $v;
$ar .= $v;
}
return $ar;
}
}
答案 0 :(得分:1)
试试这个:
$result = '';
$index = 0;
$count = count($artists);
foreach ($artists as $artist) {
if ($count >= 2) {
if ($index === 1) {
$separator = ' ft. ';
} elseif ($index === $count - 1) {
$separator = ' and ';
} else {
$separator = ', ';
}
$result .= $separator;
$index++;
}
$result .= $artist;
}
return $result;
答案 1 :(得分:0)
$result = '';
foreach ($artists as $k=>$v) {
if ($k == 1) {
$result .= ' ft. ';
} else if ($k > 1) {
if ($k <= sizeof($artists) - 2) {
$result .= ', ';
} else if ($k == sizeof($artists) - 1) {
$result .= ' and ';
}
}
$result .= $v;
}
return $result;