douken1726 2011-05-19 00:28
浏览 37
已采纳

PHP和MySQL:计算和排序数组中最常用的值然后打印

I am wanting to order my array by how many times a value comes up in that array and also then print only the highest 6 results.

This is what I have at the moment:

        $delimiter = " ";
        $tags = array();

        $sql = mysql_query("SELECT tags FROM share WHERE site_id = $id");

        while($result = mysql_fetch_assoc($sql)) {
            $tags_new = explode($delimiter, $result['tags']);
            $tags = array_merge($tags , $tags_new);
        }
  • 写回答

2条回答 默认 最新

  • douqiao5314 2011-05-19 00:34
    关注

    Hum... You can do that:

        while($result = mysql_fetch_assoc($sql)) {
            $tags_new = explode($delimiter, $result['tags']);
            foreach($tags_new as $tag){
                $tags[$tag]++;
            }
        }
    

    After, you need to sort by value, using function sort or rsort (desc).

        rsort($tags);
    

    Last, you need slice and get only 6 first:

        $high_tags = array_slice($tags, 0, 6, true);
    

    Edit: showing key and value:

        foreach($high_tags as $key => $value){
            echo "{$key}: {$value}";
        }
    

    Or just do:

        $high_keys = array_keys($high_tags);
    
        var_dump($high_keys);
    

    Bye :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)