Jump to content

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];
   }
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.