使用PHP爆炸函数

时间:2016-12-15 11:11:11

标签: php

我正在从我的数据库中提取一些信息。目前它列出了所有的兴趣/标签'。有没有办法将它限制为仅显示4?然后添加+(剩余金额)

例如:

"Interested in : Cats, Dogs, Monkeys (+5)"
<?$tags = explode(',', $usr->interests);

 foreach($tags as $tag):

 ?>

 <? echo "<span>$tag</span>,";
     endforeach; ?>

提前致谢, 杰米

2 个答案:

答案 0 :(得分:1)

explode function有一个limit参数,您可以使用它:

<?php
// Obtain the remaining tags, if the tags count is more than 4
$totalTags = (substr_count($usr->interests, ",") + 1);
$remainingTags = $totalTags > 4 ? $totalTags - 4 : false;

// Obtain the first for 4 tags
$tags = explode(',', $usr->interests, 4-$totalTags); // (third parameter, is the limit)

// Initialize a text buffer
$textBuffer = "";

foreach($tags as $tag){
    // Feed the buffer
    $textBuffer .= "<span>$tag</span>,";
}

// Remove last comma
$textBuffer = substr($textBuffer, 0, strlen($textBuffer)-1);

// Insert remaining counter into the buffer
if($remainingTags){
    $textBuffer = $textBuffer . " (+". $remainingTags .")";
}

// Use your variable wherever you want
echo $textBuffer;

?>

请注意,爆炸的Limit参数应为负数,仅返回前4个标记。有关详细信息,请参阅上述功能链接。

答案 1 :(得分:0)

您可以使用for

for($i=0;$i<4;$i++) :
if (isset($tags[$i]))
echo "<span>" . $tags[$i] . "</span>"
endfor;

if (count($tags) > 4)
echo "(+" . count($tags) - 4 . ")"; 

或者您可以使用array_slice函数将数组划分为两个数组 - 首先是长度为4,其次是所有其他元素,然后使用这两个数组。 http://php.net/manual/en/function.array-slice.php