我的 JavaScript 数组有问题。我似乎无法正确获取该值。
我在 PHP 中创建数组,如下所示:
$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)
编辑 json_encode 结果为“false”/编辑
然后我将此 $data 分配给 JS 变量作为 sdata。
然后我尝试获取 JS 中的值,但它不起作用。我收到未定义的错误。
这是我的 JavaScript:
var i = 1;
var j = 5;
if(sdata["x"] == i && sdata["y"] == j){
alert(sdata["x"]["y"]["sid"]);
}
它的目的是提醒我“sid”的值,但我得到: 未定义
有什么想法我的错误在哪里吗?
最佳答案
给定你的 json
alert(sdata["x"]["y"]["sid"]);
应该是
alert(sdata["sid"]);
因为你显示的json编码数据只是一个一维数组
编辑
如果你的 json 结果为 false,那就是另一回事了:
$data = json_encode($row);
应该在你的循环内,为了良好的实践,如果你只是编码 $row 为什么还要费心
$data[$row['x']] = Array();
$data[$row['x']][$row['y']] = $row['sid'];
否则尝试
print_r($row);
在 while 语句中并确保您的预期结果首先来自 mysql。
编辑
如果您尝试获取 json 中的 $data 变量,请使用
$data = json_encode($data);
在循环之外。
编辑
JSFiddle 返回给定 x 和 y 的 sid - 我确信它可以以更干净的方式完成,但这是一个开始 http://jsfiddle.net/HWByj/
var sdata = {"4":{"4":"1"},"7":{"1":"0"}};
var i = 4;
var j = 4;
if(typeof sdata[i] != 'undefined')
{
if(typeof sdata[i][j] != 'undefined')
{
alert(sdata[i][j]); //gives you the value of sid
}
}
关于php - 在 JS 中处理数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9694024/