Jump to content

Filter array by keyword


darkminos

Recommended Posts

Should it not be

foreach ($myArray as $subArray) {
		if(in_array($keywords, $subArray['title']) ) {
			var_dump($subArray);
		}
	}

Anyhow ... no results displayed.

 

This is what the array looks like

array(925) { [0]=> array(9) { ["pic"]=> string(53) "http://ecx.images-amazon.com/images/I/21HPIhRQNFL.jpg" ["link"]=> string(225) "http://www." ["from"]=> string(6) "A" ["title"]=> string(99) "20 x 18W, PAR38, AC100-240V, E27 Edison ES, LED Lamp, Warm White, 75W-100W Equivalent, Non-Dimmable, Bulb" ["cost"]=> string(6) "7.80" ["description1"]=> string(37) "Direct replacement for 75W-100W bulbs" ["description2"]=> string(23) "Energy saving up to 80%" ["description3"]=> string(18) "High quality light" ["category"]=> string(3) "LED" } 

 

And now if the search keyword is "led bulb" it should look for "led" and "bulb" in the ['title'], if one of the keywords is identified the result should be positive.

 

Thanks for being more specific on what you wanted. In my first example, I'm not calling in_array on a multi-dimensional array, but it still won't do what you want, as it's checking for an exact match, rather than it simply containing the keyword.

 

<?php

$keywords = array('foo','bar');

$myArray = array(
array('title'=>'blah blah blah','description'=>'key 1'),
array('title'=>'foo blah','description'=>'key 2'),
array('title'=>'blah blah bar','description'=>'key 3'),
array('title'=>'blah blah blah','description'=>'key 4'),
array('title'=>'bar blah foo','description'=>'key 5')
);

// Loop through each sub-array of myArray
foreach( $myArray as $subArray ) {
// Loop through each keyword
foreach($keywords as $keyword) {
	// Check if 'title' in the sub-array contains the current keyword
	if( stristr($subArray['title'],$keyword) !== FALSE ) {
		// If so, report it
		echo "Match found!";
		// Dump the matching sub-array
		var_dump($subArray);
		// Stop looking for more keywords for this sub-array.
		break;
	}
}
}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.