I have got my self confused on how to construct arrays correctly in PHP prior to my json encode to check them in javascript.
I'm trying to store an array of objects with their grid reference (x,y)
So i do this in php:
$get = mysql_query("SELECT x,y,sid FROM $table WHERE uid='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($get)) {
$data[$row['x'].$row['y']] = $row['sid'];
}
//print_r($data);
$data = json_encode($data);
In javascript i then try to check if a object exists on a given co-ordinate so i try this:
for (i=0;i<tilesw;i++){ //horizontal
for (j=0;j<tilesh;j++){ // vertical
if(sdata[i.j]){
alert(sdata[i.j][sid]);
}
}
}
sdata is my array after json encode.
My json encode looks like this:
{"44":"0","21":"0"}
Problem is i get : Uncaught SyntaxError: Unexpected token ] on the alert line.
Also is my approach correct or is there a better way to construct my array?
1 Answer 1
You have a JavaScript syntax error in your code. There is an extra ] on your alert() line.
alert(sdata[i.j][sid]]);
Should be
alert(sdata[i.j][sid]);
If you're actually trying to concatenate the values i and j you also need to be using + rather than ., so you would use i.toString()+j.toString() as the key rather than i.j.
Example of using this with two-dimensional arrays:
PHP
$arr = array();
while($row = mysql_fetch_assoc($get)) {
if(!isset($arr[$row['x']])) $arr[$row['x']] = array();
$arr[$row['x']][$row['y']] = $row['sid'];
}
$data = json_encode($arr);
JavaScript
for(var x in sdata) {
for(var y in sdata[x]) {
alert('Object found at coordinates ' + x + ',' + y + ' ' + sdata[x][y]);
}
}
6 Comments
i and j were integers. I've updated my answer once more.array($row['x'] => array($row['y'])); as the return object so you can simply iterate over the values in the array to determine which cells have objects rather than brute forcing it.
i.jattempting to accomplish? This is invalid javascript syntax.sdata[i.toString() + j.toString()](or some reasonable facsimile.)sdata[i + '' + j]..any addition operation with a string will cause all subsequent addition operations to be string concatenations regardless of type.