Wed. Oct 16th, 2019

Codes

Codes for Coders

Relevant data search using Array sort Php

1 min read
Relevan data search using Array sort Php

Relevan data search using Array sort Php

PHP provides a range of functions for sorting data based on either the key or value of an associative array. Where it gets complicated is when you need to sort an array of associative arrays by one or more conditions.

This is a very common task for PHP programmers as data returned from database/SQL queries often appears in associative array format.

Here we are going to sort an array in most relevant order using a keyword.

 

PHP usort() Function

The usort() function sorts an array using a user-defined comparison function.

Syntax

usort(array,myfunction);
<?php
function my_sort($a,$b)
{
if ($a==$b) return 0;
return ($a<$b)?-1:1;
}
$a=array(4,2,8,6);
usort($a,"my_sort");
$arrlength=count($a);
for($x=0;$x<$arrlength;$x++)
{
echo $a[$x];
echo "<br>";
}
?>

Output: 
2
4
6
8

Php similar_text Function

The similar_text() function calculates the similarity between two strings.

It can also calculate the similarity of the two strings in percent.

Syntax

similar_text(string1,string2,percent)
<?php
similar_text("Hello World","Hello Peter",$percent);
echo $percent;
?>

Output:
63.636363636364

Now we will use usort() and similar_text() to sort array for most relevant data:

 

<?php
$arr = array('Banana','Mango','Apple','Pinapple','Graps','Guava');

$userinput = 'ap';

usort($arr, function ($a, $b) use ($userinput) {
similar_text($userinput, $a, $percent_a);
similar_text($userinput, $b, $percent_b);
return $percent_a === $percent_b ? 0 : ($percent_a > $percent_b ? -1 : 1);
});
?>

Output:
Array ( [0] => Graps [1] => Pinapple [2] => Guava [3] => Apple [4] => Mango [5] => Banana )
Relevant data search using Array sort Php

Leave a Reply

Your email address will not be published. Required fields are marked *