doushichi3678 2015-10-12 16:23
浏览 39
已采纳

如何根据最相关的值过滤和排序数组?

Suppose I have an array which is in the below:

Array
(
    [0] => Array
        (
            [name] => playstation sony 3 slim 320gb
        )

    [1] => Array
        (
            [name] => sony xperia acro s
        )

    [2] => Array
        (
            [name] => sony xperia tipo
        )

    [3] => Array
        (
            [name] => sony ericsson xperia arc s
        )

    [4] => Array
        (
            [name] => sony xperia go
        )

    [5] => Array
        (
            [name] => sony playstation 4
        )

)

Now I want to filter the array based on the search value and sort the array by the based on most relevant (by shortest length).

My request data is:

 $request = 'sony';

I'm expecting the following results:

 Array
(
    [0] => Array
        (
            [name] => sony xperia go
        )

    [1] => Array
        (
            [name] => sony xperia tipo
        )

    [2] => Array
        (
            [name] => sony playstation 4
        )

    [3] => Array
        (
            [name] => sony xperia sony acro ss
        )

    [4] => Array
        (
            [name] => sony ericsson xperia arc s
        )

    [5] => Array
        (
            [name] => playstation Sony 3 slim 320gb
        )

)
  • 写回答

1条回答 默认 最新

  • dongxi7704 2015-10-12 20:15
    关注

    The simplest way to achieve your search filtering in PHP is to filter array (array_filter) by your custom callback then sort it using a user-defined comparison function (usort).

    Here is a simple code:

    <?php 
    $data[]['name'] = 'foo';
    $data[]['name'] = 'playstation sony 3 slim 320gb';
    $data[]['name'] = 'sony xperia acro s';
    $data[]['name'] = 'sony xperia tipo';
    $data[]['name'] = 'sony ericsson xperia arc s';
    $data[]['name'] = 'sony xperia go';
    $data[]['name'] = 'sony playstation 4';
    $data[]['name'] = 'bar';
    
    $result = array_filter($data, function($v) { return stristr(current($v), 'sony'); });
    usort($result, function($a, $b) { return strlen(current($a)) < strlen(current($b)) ? -1 : 1; });
    print_r($result);
    

    Please note that PHP is not a good solution for implementation of complex search requirements. So for more search-oriented solutions, please consider using:

    which can be easily integrated with PHP.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?