dourao3960 2013-12-27 01:28
浏览 12
已采纳

如何检测数组中的类似值?

Say I have a list of genres that looks something like:

$genres = array(
    'soul', 
    'soul jazz', 
    'blues', 
    'jazz blues', 
    'rock', 
    'indie', 
    'cool jazz', 
    'rock-blues');

...And so on, for 762 values. How can I organize these genres into categories?

For example, I would want the Blues category to contain 'blues', 'jazz blues', and 'rock blues.' I would want the Jazz category to contain 'soul jazz', 'jazz blues', and 'cool jazz.'

Any and all help is appreciated.

  • 写回答

2条回答 默认 最新

  • drlnwji79147769 2013-12-27 01:53
    关注

    Using preg_match would be one the best ways to solve your problem.

    <?php
    $categories = array("blues", "jazz");
    $genres = array("soul", "soul jazz", "blues", "jazz blues", "rock", "indie", "cool jazz", "rock-blues");
    $arr = array();
    $others = array();
    foreach($genres as $genre){
    $num = 0;
        foreach($categories as $category){
            if(preg_match("/\\b".$category."\\b/", $genre)){
            $arr[$category][] = $genre;
            $num = 1;
            }
        }
        if($num == 0){
        $others[] = $genre;
        }
    }
    ksort($arr);
    $arr["others"] = $others;
    unset($genre, $num, $category, $others);
    print_r($arr);
    ?>
    

    The result will be:

    Array
    (
        [blues] => Array
            (
                [0] => blues
                [1] => jazz blues
                [2] => rock-blues
            )
    
        [jazz] => Array
            (
                [0] => soul jazz
                [1] => jazz blues
                [2] => cool jazz
            )
    
        [others] => Array
            (
                [0] => soul
                [1] => rock
                [2] => indie
            )
    
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行