Order Array by Relevant Search Results - php
I know that there has to be a library for this somewhere, but what I am trying to do is pass in an array of strings, and a search string and have it order the array by how relevant it is to the search string.
I have been having a hard time figuring out what to google to figure this out, anyone point me in the right direction?
preferably in php, or another server side language
I don't really know what you mean by 'revelant'..
But, if you want to find the best string based on a search string, you can use the Levenshtein algorithm. It calculate a "distance" between two strings.
More infos here : http://php.net/manual/fr/function.levenshtein.php
This is kinda tricky and I cannot really explain in English, so I'll just have to show you a working code. If you have an questions, you can ask.
<!DOCTYPE html>
<head>
<title>Search Array</title>
<script>
//so let's set an array of values we will be searching
function searchArray(dis) {
var bigContent = new Array('Jesus loves you','Angle','God in Heaven','Bala','Overcomer','Be born again','Adesuwa','Heaven is real','James','Apple','John the baptist');//this is the array that serves as your database
var searchi = dis.value, result = Array();
searchi = searchi.toLowerCase();
//order the array alphabetically
bigContent = bigContent.sort();
var content;
if(searchi !='') {
//Define the arrays for initial pre-storage
var keys = new Array(), contentArray = new Array();
//Loop through the content array to search for all occurence of string
for(var i=0;i<bigContent.length;i++) {
content = bigContent[i].toLowerCase();
if(content.indexOf(searchi) > -1) {//found the search in this value
//get the position of the search string in content
var pos = content.indexOf(searchi);
//make position the key for your content array
if(contentArray[pos]) {//check if this position has already been assigned to a content
//if yes, append this content.
contentArray[pos] += '[]'+bigContent[i];
} else {//else, set the content
contentArray[pos] = bigContent[i];
//only save the position the first time you find it, to avoid duplication
keys[keys.length] = pos;
}
}
}
//sort the key so it can order the values in ascending order(relevance)
keys = keys.sort();
//loop thru the key
for(var i=0;i<keys.length;i++) {
var key = keys[i];//remember the value of "var key" is the key for contentArray value
if(contentArray[key]) {//just to be sure it's ther
var thisContent = contentArray[key];
//check if the content has more than 1 value
if(thisContent.indexOf('[]') < 0) {//if it doesn't
result[result.length] = contentArray[key];
} else {//if it does
//convert content into array
var thisContentAr = thisContent.split('[]');
//Loop thru the array
for(var j=0;j<thisContentAr.length;j++) {
result[result.length] = thisContentAr[j];
}
}
}
}
}
document.getElementById('ov').innerHTML = '';
for(var i = 0; i<result.length;i++) {
document.getElementById('ov').innerHTML += '<div>'+result[i]+'</div>';
}
}
</script>
</head>
<body>
<div><input type="text" onkeyup="searchArray(this);" autofocus="autofocus" /></div>
<div id="ov"></div>
</body>
</html>
Related
Looking for an element in an array in PHP
I don't know if I'm managing this array in the best way. The array I have is this: $bass = $_POST['bass']; $selected_scale = $_POST['scale']; $major_scales = array ( array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",), array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",), array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",), array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"), array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"), array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"), array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"), array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"), array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"), array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"), array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"), array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"), array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"), array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"), array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"), array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"), array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"), array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"), array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"), array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"), array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb") ); $bass is a string, like the one inside the arrays. The $selected_scale is just a number. What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that. But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop: // if value exists in mentioned index if (in_array($bass,$major_scales[$selected_scale])){ // index of that value in that array $tmp_ind = array_search($bass,$major_scales[$selected_scale]); // length of the array $len = count($major_scales[$selected_scale]); // store values after this value $res = []; for ($i=$tmp_ind;$i<$len;$i++){ $res[$i] = $major_scales[$selected_scale][$i]; } } print_r($res); Demo1 If you need to find value by index $selected_scale in one of these arrays and also store values after this position: foreach($major_scales as $ar){ if ($ar[$selected_scale] == $bass){ // length of the array $len = count($ar); // store values after this value $res = []; for ($i=$selected_scale;$i<$len;$i++){ $res[$i] = $ar[$i]; } } } print_r($res); Demo2
javascript equivalent to php max for arrays
I have a function in php that selects the array with that contains the most elements. $firstArray = array('firstArray','blah','blah','blah'); $secondArray = array('secondArray','blah','blah'); $thirdArray = array('thirdArray','blah','blah','blah','blah'); then I get the name of the variable with the highest length like this: $highest = max($firstArray, $secondArray, $thirdArray)[0]; but I am developing an application and I want to avoid using php and I have tried javascript's Math.max() to achieve the same results but it doesn't work the same way unless I do Math.max(firstArray.length, secondArray.length, thirdArray.length) But this is useless since I need to know the name of the array that contains the most elements. Is there any other way to achieve this?
This function takes as input an array of arrays, and returns the largest one. function largestArray(arrays){ var largest; for(var i = 0; i < arrays.length; i++){ if(!largest || arrays[i].length > largest.length){ largest = arrays[i]; } } return largest; } We can test it out with your example: firstArray = ['firstArray','blah','blah','blah']; secondArray = ['secondArray','blah','blah']; thirdArray = ['thirdArray','blah','blah','blah','blah']; // should print the third array console.log(largestArray([firstArray, secondArray, thirdArray]));
The following url has a max() equivalent. It supports more then just numbers just like in php: js max equivalent of php
If you feel ok with including 3rd-party libs, maybe http://underscorejs.org/#max does what you want: var aList = [firstArray, secondArray, thirdArray]; _.max(aList, function(each) { return each.length; });
how to Check values present in javascript array or not
here is my javascript array alert(Parameter); it alerts: Eqt_Param0=4.00,Eqt_Param1=0,Eqt_Param2=0 Now what I am trying to do is if any of the array elements values are equal to '0` i need to alert 'array does not contain all values,', so how to check whether array is empty or not.
It looks like your array is a set of values of the form "key=number", and you want to know if any of the numbers are equal to zero. The "proper" way to do it is: var l = Parameter.length, i; for( i=0; i<l; i++) { if( Parameter[i].split("=")[0] == "0") { alert("Array does not contain all values"); break; } } But you could just hax it: if( (Parameter.join(",")+",").indexOf("=0,") > -1) { alert("Array does not contain all values"); }
Php javascript conflict with passing javascript to php
I have a slight problem. I have several arrays in php with different team names. Each array contains teams of a certain league. When I click an add button I get the option to add a new entry to the calendar. I want the drop down to have only the teams for that league. onclick of the add button I call a javascript function that knows what division was clicked. However in order to give the javascript the information for which teams to display I have to pass it one of the php arrays. The problem I am having is telling php which array to pass to javascript depending on which league javascript is on. I don't want to specify the array myself because there is an option to add a league and this would mean having to code in more code each time a league is added. The point of the site is being dynamic. here is some code. for ($i = 0;$i<$sizeof($leaguesarray);$i++){ $htmlimploded[$i] = implode($html[$i]); } here I have used emplode to make all of my php arrays readable into javascript. for (var h = 0; h<size; h++){ // goes through every league if(h == leaguenum){ // finds the league for the clicked add button // this is the line that I have trouble with I can't think of //anyway of telling it which array to use since it is serverside code. var myarray = ["<? echo $htmlimploded[]?>"]; } } Javascript code above.
Imploding works but why not json_encode($array)? It's a simpler, built in way to turn php arrays into javascript objects or arrays. If you have something like: $league1 = array('team1', 'team2'); $league2 = array('team3, 'team4') ; Then make a multidimensional associative array of these: $all_teams = array('league1'=>$league1, 'league2'=>$league2); encode it into a Javascript object and print it into your JS: $encoded = json_encode($all_teams); print 'var teamObject = '.$encoded.';'; If you were to console.log(teamObject) you'd see something like this: {"league1": ["team1", "team2"], "league2": ["team3", "team4"]} Looks complicated, but now you can pull out the array you desire very easily. The league 1 array is teamObject.league1 and the league2 array is teamObject.league2, and so on.
i think you missed something in the following code: var myarray = ["<? echo $htmlimploded[]?>"]; By right, it should be: var myarray = ["<?php echo $htmlimploded[]?>"];
Assuming that PHP knows the names of the leagues and the teams and that JavaScript knows the league name that is clicked, You can wrap the arrays of the team names inside an object with the league as the name of the property. <?php $arr = array("League1" => array("Team 1", "Team 2"), "League2" => array("Team 3", "Team 4") ); ?> var obj = {}; <?php foreach ($arr as $k => $v): ?> obj.<?php echo $k; ?> = ["<?php echo implode('","', $v); ?>"]; <?php endforeach; ?> Then when a user selects a league, you can loop through the array of the property (which is the league name) of the object. clickedLeague = "League1"; for (var i = 0; i < obj[clickedLeague].length; i++) { console.log(obj[clickedLeague][i]); // Logs the team name to console }
assigning value to array in javascript
in php you could do like this: $key1 = 1; $key2 = 1; $array[$key1][$key2] = 'hi'; in javascript i tried with this: key1 = 1; key2 = 1; var array = new Array(); array[key1][key2] = 'hi'; but it didnt work. how can i do the same thing in javascript?
Your problem is that you need to instantiate the inner array before assigning values in it var key1 = 1; var key2 = 1; var array = []; array[key1]=[]; array[key1][key2] = 'hi'; Or you could do it all in one: var array=[['hi']] Also, you should avoid assigning to specific indexes unless you're updating an existing element. The first example above will automaticly add an element array[0]=undefined; If you want to use specific keys, and not just indexes, you should use dictionaries or objects (dictionaries and objects are the same thing i javascript)
The key1 property of array is undefined at the time you are trying assign the property key2 to it. You need to actually indicate that array[key1] is an array before you start assigning values to it. For example: array[key1] = []; array[key1][key2] = 'hi';
JavaScript is having a problem with the key1 and key2 dimensions of your array being undefined. To correct this problem, these are changes you could make: var key1 = 1; var key2 = 1; // define "array" as an empty array: var array = []; // define "array[key1] as an empty array inside that array // (your second dimension): array[key1] = []; array[key1][key2] = 'hi'; PHP does some magic -- you can simply supply 2 keys and PHP "knows what you mean" and will define the $key1 and $key2 dimensions without thinking about it. See: PHP: arrays: If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. JavaScript requires you to be more explicit about array creation.
You can find neat implementations. For example, here is a way, which is a function creating an array for the rows and then, creating an array for each column (could be anidated in the other way, but...) var sDataArray=MultiDimensionalArray(7,2); //alert(sDataArray[0][0]); function MultiDimensionalArray(iRows,iCols) { var i; var j; var a = new Array(iRows); for (i=0; i < iRows; i++) { a[i] = new Array(iCols); for (j=0; j < iCols; j++) { a[i][j] = ""; } } return(a); } The thing is, you just can't work the arrays just like PHP ones. Must treat them the way they really are: an array of arrays (of arrays (of arrays (of arrays)...)). Good luck.