在标签云中为每个循环限制a

| 我有以下标签云。
$rows = $db->loadObjectList();
foreach ($rows as $row)
{
$strAllTags .= $row->caption . \",\"; 
}

// Store frequency of words in an array
$freqData = array(); 

// Get individual words and build a frequency table
foreach( explode(\",\", $strAllTags) as $word )
{
// For each word found in the frequency table, increment its value by one
array_key_exists( trim($word), $freqData ) ? $freqData[ trim($word) ]++ : $freqData[ trim($word) ] = 0;
}


function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 32 )
{
$minimumCount = min( array_values( $data ) );
$maximumCount = max( array_values( $data ) );
$spread       = $maximumCount - $minimumCount;
$cloudHTML    = \'\';
$cloudTags    = array();

$spread = 55;

foreach( $data as $tag => $count )
{
            if ($count > 4)
            {
    $size = $minFontSize + ( $count - $minimumCount ) 
        * ( $maxFontSize - $minFontSize ) / $spread;
    $cloudTags[] = \'[[a style=\"font-size: \' . floor( $size ) . \'px\' 
    . \'\" class=\"tag_cloud\" href=\"/home?func=search&searchfield=\' . $tag 
    .  \'\"]]\' 
    . htmlspecialchars( stripslashes( $tag ) ) . \'[[/a]]\';
           }
}

return join( \"\\n\", $cloudTags ) . \"\\n\";
}   
echo getCloud($freqData);
?>
它工作正常,我只需要将其限制在前20个结果之内,关于如何做到最好的任何想法? 谢谢,让我知道是否需要查看其余的代码。     
已邀请:
如果您的数组尚未排序,则可以使用
arsort()
将其按最高结果排序。然后,您可以使用
array_slice()
创建一个仅包含前20个数组元素的新数组:
arsort($data);
$data = array_slice($data, 0, 20);
“ 4”表示“关联反向排序”。这仅表示它作用于关联数组,并维护其键,并按值的“反向”(即从高到低)顺序对数组进行排序。 “ 5”只是“切片”现有阵列。在此示例中,它说“ \”采用ѭ6return数组,并从第一个数组开始返回一个包含其值20的新数组。 为了解决您在注释中提出的要点,当您希望标签是随机的时,标签也将按大小显示。在获取前20条记录后,可以通过在数组上使用ѭ7来完成此操作:
arsort($data);
$data = array_slice($data, 0, 20);
shuffle($data);
    
取另一个计数器变量并循环递增,然后检查是否达到20中断循环 要么 使用array_slice
$data = array_slice($data, 0, 20);

foreach( $data as $tag => $count )
{
.....
    

要回复问题请先登录注册