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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b