Istiak Mahmood
Istiak Mahmood

Reputation: 2422

How to filter and sort the array based on the most relevant values?

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
        )

)

Upvotes: 0

Views: 189

Answers (1)

kenorb
kenorb

Reputation: 166359

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.

Upvotes: 3

Related Questions