[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 337
  • Last Modified:

Search a PHP array for a string and sort by the number of matches (relevancy)

I have a PHP array containing a series of text articles and would like to be able to search for a string inside it then sort the results according to the number of occurrences discovered. For example if I looked for the word 'cat' it would return all the records containing the word 'cat' sorted by the number of times it was found in each one of the records within the array. Would anyone be able to help me with the PHP code?
Thanks in advance for your help
0
fdran
Asked:
fdran
  • 2
1 Solution
 
Rok-KraljCommented:
Here you go...

the first result is then $return[0][1], the second is $return[1][1] und so weiter...
<?php
	$texts=array(
		'this is this is this',
		'this is only once',
		'this is this twice'
	);
	$word='this';

	$return=array();
	foreach($texts as $text) {
		$return[]=array(substr_count($text, $word), $text);
	}

	sort($return);
	print_r($return);
?>

Open in new window

0
 
fdranAuthor Commented:
Thank you Rok-Kralj,
What if the array was multidimensional?
0
 
Rok-KraljCommented:
Miltidimensional - how? Post an example or explain what you mean.

Then you make it one dimensional and apply same code.
0

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now