I have really done what I think is a not-code-review-passing hack to pass a 2-dimensional array from PHP to Javascript. The outer array has elements, and each of its elements is an array.
Each inner array consists of 4 fields from my database records. The inner array elements are: the name of a town, its latitude and its longitude, and an integer index.
Is the code working? Yes. But I'm hating the fact that I am 99% convinced that, as a fairly raw beginner, there is a much better way to create then pass a 2d array from PHP to Javascript and I need to know how, as I hacked this together through trial-and-error and reading lots of SO posts, and did not create this from a priori know-how, wisdom or confidence.
Each outer array element is an array that (needs to) look like this:
top
array:
[0] = ["Campbell", 37.21, 122.0, 0]
[1] = ["Sunnyvale", 37.54, 121.37, 1]
[2] = ["Saratoga", 37.24, 122.001, 2]
[3] = ......etc. etc...........
Note that the 2nd level arrays have a string, then a float, then another float, then an integer.
Here's the code in PHP that packages my database records into a 2-d PHP array (error checking, other code is not shown, for clarity):
$result = mysql_query($query);
$numrows = mysql_num_rows($result);
$outerArray = array();
for($i = 0; $i < $numrows; $i++)
{
$theRow = mysql_fetch_row($result);
$city = $theRow[1];
$lat = $theRow[22];
$lng = $theRow[23];
$outerArray[] = array($city, $lat, $lng, $i);
}
$latLngValues = json_encode($outerArray);
// EDIT: ADDED TO TELL ME WHAT THIS 2d ARRAY ACTUALLY LOOKS LIKE
var_dump($latLngValues);
In the onload handler for my web page, I call a javascript function and pass this array:
<body onload='handleLoad(<?php echo $latLngValues ?>)'>
Here is my handleLoad():
function handleLoad( latLng2dArray )
{
for (var i = 0; i < latLng2dArray.length; i++)
{
var town = latLng2dArray[i];
var latitude = Number(town[1]);
var longitude = Number(town[2]);
// I USE THE DATABASE RECORD'S NUMBERS TO CREATE A Gmaps LatLng
var myLatLng = new google.maps.LatLng(latitude, longitude);
}
There's probably a cleaner, and/or more efficient, way to do this.
For example, I found that if I did not use the Number() function to 'force' my database numbers into a number, the call to "new google.maps.LatLng(latitude, longitude)" was giving me NaN.
So I'm hoping more experienced people can let me know a cleaner way. While this code works, I hacked at it for a day through trial and error.
EDIT: I used a var_dump() in my php code to see what the 2d array "$latLngValues" looks like just before it's passed to my onload handler, and "$latLngValues" looks like this:
string(133) "[["Campbell","37.2724","-122",0],["Sunnyvale","37.2724","-122",1],["LosGatos","37.2607","-122",2],["Saratoga","37.2607","-122.046",3]]"
I want to point out this: in my database, the data type I used is 'float' for the latitude and longitude. Not sure how/why the var_dump shows them as a string (not floats) while the integer index is treated correctly, and not a string.
No one offered a better coding strategy so for now, I'm going with the existing code above -- it aint pretty but it works. I'll post back if a more-correct way is found.
Related
I send a php array like:
$var = array (
0=> 4,
1=> 6,
2=> 8,
...
as json_encode($var); into the uri and then I receive it into javascript file is still ok here but when I push it into new array like this :
this.patg.push(attd);
Is inserted like this below .
var attds = ["4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606"]
I know I have to find the problem. but
Questions:
could you please tell me why this could happends or help me to deal with it.
but in any case just for knowledge . how you would add the extra " " surrounding the , that i miss to be an array , or is that crazy idea to fix this?
If you are receiving a string value and you want to use it as an array of integers you should split it into an array first:
var receivedData = "4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606";
var dataArray = receivedData.split(",");
Afterwards you can use it with another array, however be aware that if you already have a defined array into which you want to push the dataArray you shouldn't push but concat instead.
In other words if you have:
var previousArray = [1,2,3];
previousArray.push(dataArray);
You will get
[1,2,3,[4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]]
meaning that the whole array is pushed onto the 4th position of previousArray.
If, on the other hand, you concat the arrays will merge:
var previousArray = [1,2,3];
previousArray.concat(dataArray);
[1,2,3,4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]
Source: http://www.w3schools.com/jsref/jsref_concat_array.asp
I'm trying to rewrite some old VBScript as Javascript for an ASP.NET application and there is one line I'm not sure how to translate, and I'm not even entirely positive what it's doing.
The application essentially allows the user to enter in a new employee number to add to the database and then assign it user permissions. Don't ask me why the code is such a mess, I didn't write it originally, I'm just trying to make it work in Chrome
here's the relevant code that i've managed to translate so far:
if(form1.txtEmpno.value != ""){
var oOption;
oOption = document.createElement("OPTION");
oOption.text=form1.txtEmpno.value;
oOption.value=form1.txtEmpno.value;
form1.lstActive.add (oOption);
oOption = document.createElement("OPTION");
oOption.text="";
oOption.value="";
form1.lstPerms.add (oOption);
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value;
arrUsers(1,ubound(arrUsers,2)) = "";
form1.txtEmpno.value = "";
oOption = null;
}
here's the line in question:
redim preserve arrUsers(1,ubound(arrUsers,2)+1);
MSDN defines ReDim [Preserve] varname(subscripts) as:
The ReDim statement is used to size or resize a dynamic array that has already been formally declared using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). You can use the ReDim statement repeatedly to change the number of elements and dimensions in an array.
If you use the Preserve keyword, you can resize only the last array dimension, and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array.
Arrays in JavaScript have different semantics to VBScript's arrays, especially in that they're actually closer to a vector than a true array, furthermore JavaScript does not provide for true N-dimensional arrays: instead you use staggered-arrays (arrays-within-arrays). Which means your VBScript cannot be syntactically converted to JavaScript.
Here's your relevant code in VBScript:
ReDim Preserve arrUsers(1,ubound(arrUsers,2)+1)
arrUsers(0,ubound(arrUsers,2)) = form1.txtEmpno.value
arrUsers(1,ubound(arrUsers,2)) = ""
We see that arrUsers is a 2-dimensional array. This will need to be converted into a staggered array, but you haven't posted the code that defines and initializes arrUsers, nor how it is used later on, so I can only work from making assumptions.
It looks to be adding 1 element to the last dimension, but the code only seems to use the extra space in the [1] subscript (i.e. it only wants the extra dimensional space for certain values of the 0th dimension instead of all values), which makes this simpler as you don't need to iterate over every 0th-dimension subscript.
JavaScript arrays have numerous function-properties that we'll use, in particular push: which appends an element to the end of an array (internally growing the buffer if necessary), and pop which removes the last (highest-indexed) element from an array (if an array is empty, it's a NOOP):
var arrUsers = [ [], [] ]; // empty, staggered 2-dimensional array
...
arrUsers[0].push( form1.txtEmpno.value );
arrUsers[1].pop();
Much simpler.
However, if this array is just part of some internal model to store and represent data then you should take advantage of JavaScript object-prototypes instead of using array indexes, as that makes the code self-describing, for example:
var User = function(empNo, name) {
this.employeeNumber = empNo;
this.name = name;
};
var users = [];
users.push( new User(1, "user 1") );
users.push( new User(23, "user 23") );
...
for(var i = 0; i < users.length; i++ ) {
alert( users[i].name );
}
I have a file called translations.js, this js does got have two vars. This two vars are containing over 20.000 words.
var english = ["word1", "word2", "word3", "word4", ...]
var farsi = ["translation1", "translation2", "translation3",
"translation3"]
So i want to add all the values to a table on mySQL.
How can I do that quick and good? I want to do this with PHP.
I have the table "translations", containing this columns: id, english, farsi.
I want that all the words should be added into the database. So i thought to split this file into english.js and farsi.js - after that I wanted to use "explode" on both variables, foreach till no "" is there and then i wanted to add them step by step.
Is there a easier way? Does this way make sense?
Thank you!
If those arrays are valid json by themselves you could make a json file for each and read the file using file_get_contents(), then use json_decode() to convert to php array.
Loop over array to do inserts.
Alternative would be to load those variables into an html page and use ajax to post the whole array to php script. Loop over array received in $_POST
Does have english array and farsi array exactly the same size?
(I suppose yes).
Maybe you can create a file english.json and a farsi.json;
each file must only contains ["word1", "word2", "word3"] so remove var english =.
then use
$listEnglish = json_decode(file_get_contents('path_to_english.json'));
$listFarsi = json_decode(file_get_contents('path_to_farsi.json'));
It should generate a php array for each one.
finally loop on it
for($i = 0; $i < sizeof($listEnglish); $i++)
{
$englishWord = $listEnglish[$i];
$farsiWord = $listFarsi[$i];
//Then you insert
INSERT INTO translation(english, farsi) VALUES ($englishWord, $farsiWord);
}
I can't understand this code. Before entering into the body:
I cant upload text with English. I definitely see array declaration myArray = new Array(); but suddenly I see myArray[i]= new array();. Another I see myArray[i][j]
What's happening?
i know that
if i want using method array
i can use myArray = new array(5);
AND
i know that "my Array " = new array();
" " this part just function only name
not using another function
but this code means 'you are wrong'
i need that this part need understanding
PS. thanks for editing and answering:)
i see those
so i need to edit
and i want see former writing
myArray is an array of arrays. Each i element of myArray[i] is an array itself. You can picture it as a 2-d grid, like a cheessboard (8x8 squares):
myArray[0][0] myArray[0][1] ... myArray[0][7]
myArray[1][0] myArray[1][1] ... myArray[1][7]
. .
. .
. .
myArray[7][0] myArray[7][1] ... myArray[7][7]
Your code is building an HTML table using a two-dimensional array.
myArray = new Array(); creates the first array. In the while loop, you are building the first dimension of the array when setting a value to myArray[i]. By calling myArray[i] = new array();, you are making that value another array.
The first while loop is going to create as many rows of those 5 values in titleArray as long as you keep confirming. The second of code after that is building an HTML table with a default 1st followed by as many as you confirmed in the first loop, and each will be composed of 5 .
Hope this helps!
Let me start by explaining the situation:
I have a MySql table that contains several columns, of which a user id, a race id, a lap time, a lap number and I want to put this information into an array in PHP which I will then send to a java script.
My JavaScript array should end up looking like this :
first row:
[laptime1 user1, laptime2 user1, laptime3 user1,...]
second row:
[laptime1 user2, laptime2 user2, laptime3 user2,...]
Here's my current situation:
I first tried to test this situation for a single user and ran into lots of problems because my lap times in MySql are floats and when using json_encode it turned everything into strings, which did not work for my javascript as it started outputting the wrong values.
For example:
The first value was "8" instead of "84,521", then the second value was "4", etc..)...
Sadly, I found a potential solution with the numeric check option, but cannot use it as my hosting runs a PHP version that doesn't support it.
So I found the following solution, which I fiddled with a bit and that works for a single user (it might look messy to you, I'm really a beginner and punching above my weight, but it works) :
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
while(($result = mysql_fetch_array($query))) {
$data[] = (float)$result['racelaptime'];
}
$script = $script . "\nvar myArray = new Array(";
foreach ($data as $key => $value){
if ($key < (count($data)-1)){
$script = $script . $value . ',';
}
else {
$script = $script . $value . ");\n";
}
}
This outputs an array in JavaScript that looks like this :
myArray=[84.521,83.800,81.900]
Which is great, as this is exactly what my java script requires as input (time in seconds, separated by commas for each lap).
Now I would like to implement the multiple user element but I'm stumped as to how I can work that out...
My MySQL query is still sorted by race lap but I also kind of need to sort the data by user id as I want all the laps of each user sorted in 1 row, Also, the user id is unknown to me and can vary (depends which user posts the time) so I can't really do a "if userid==1 save this here and then go to next one".
Should I use a foreach statement in the while loop that stores the data, but how can I tell him to store all the laps by the same user in the first row (and the next user in the second row, etc...) without using tons of SQL queries ?
If you can offer a more elegant solution than my current one for passing the PHP array to JavaScript, I would be more than happy to make changes but otherwise a simple solution using the current "setup" would be great too (hope it's all clear enough).
Any help would be very much appreciated, thanks in advance !
For multiple user element I would use a multidimensional array >
$query = doquery("SELECT racelaptime,userid FROM {{table}} WHERE raceid='1' ORDER BY racelap", "liverace");
// Loop the DB result
while(($result = mysql_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['userid'], $data)){
// Create array for current user
$data[$result['userid']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['userid']][] = $result['racelaptime'];
}
// Echo json data
echo json_encode($data);
Now what you need to do on the Javascript side when handling this array is to go through each of the user
$.each(data, function(key, value){
// Use parseFloat to keep the decimal value
alert(key + ' Has the following values - ' + value);
// If you want to display the racing values you simply
$.each(value, function(k, parseFloat(v)){
alert(v);
})
})
Is this what you needed or am I completely out of the scope?