Jump to content

search an array for results


The Little Guy

Recommended Posts

How can I order an array by relevance to another string?

Lets say I have an array with the following:

 

- what does php2 stand for?

- what does html stand for?

- what does php stand for?

- what does js stand for?

- what does css stand for?

- what does php5 stand for?

 

and say the string to search for is: "what does p"

the returned results from the array would then be:

 

- what does php stand for?

- what does php2 stand for?

- what does php5 stand for?

 

I hope this makes sense, any suggestions how to do this?

Link to comment
https://forums.phpfreaks.com/topic/186124-search-an-array-for-results/
Share on other sites

here you go, hope its helpful

 

<script type="text/javascript">
var array = new Array("what does php2 stand for?","what does html stand for?","what does php stand for?","what does js stand for?","what does css stand for?","what does php5 stand for?");
var result = new Array();
var str = "what does p";

var regExp = new RegExp("^"+str);

for(i=0;i<array.length;i++) {
   if (regExp.test(array[i])) {
      result.push(array[i]);
   }
}

alert(result);
</script>

Hmm...

 

The loop works, the alert that is in the loop works but the if() inside the loop does not....

 

// suggestions array is generated from ajax
var result = new Array();
var str = ibox.vaule;  // ibox.value comes from a textbox
var regExp = new RegExp("^"+str);
for(var i in suggestions){
alert(suggestions[i]);
if(regExp.test(suggestions[i])){
	result[i] = suggestions[i];
}
}

 

Is something wrong?

I think your code should be, it all depends on whats in str, it just a simple regular expression checking for the text at the start of each expression.

 

// suggestions array is generated from ajax
var result = new Array();
var str = ibox.value;  // ibox.value comes from a textbox
var regExp = new RegExp("^"+str);
for (var i in suggestions){
   alert(suggestions[i]);
   if(regExp.test(suggestions[i])){
      result[i] = suggestions[i];
   }
}

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.