I have a problem with my arrays in JavaScript. I can’t seem to get the value correctly.
I create my array in PHP like this:
$data = Array();
$get = mysql_query("SELECT x,y,sid FROM table WHERE uid='1'");
while($row = mysql_fetch_assoc($get)){
$data[$row['x']] = Array();
$data[$row['x']][$row['y']] = $row['sid'];
}
$data = json_encode($row)
EDIT The json_encode comes out as “false” /EDIT
I then assigned this $data to a JS variable as sdata.
So then i try to get the value in JS but its not working. I get an undefined error.
This is my Javascript:
var i = 1;
var j = 5;
if(sdata["x"] == i && sdata["y"] == j){
alert(sdata["x"]["y"]["sid"]);
}
Its meant to alert me the value of “sid” but i get:
Undefined
Any ideas where my mistake is?
Given your json
should be
as the json encoded data you show is only a one dimensional array
EDIT
If your json comes out as false, that’s a different story:
Should be inside your loop, for good practice, and if you’re just encoding the $row why even bother with
Otherwise try
within your while statement and make sure your expected result is coming through from mysql in the first place.
EDIT
If you are trying to get the $data variable in json then use
outside of your loop.
EDIT
JSFiddle to return sid for given x and y – I’m sure it can be done in a cleaner way, but it’s a start
http://jsfiddle.net/HWByj/