简体   繁体   English

PHP和JavaScript语法中的数组

[英]Arrays in php & javascript syntax issues

I have got my self confused on how to construct arrays correctly in PHP prior to my json encode to check them in javascript. 我对如何在json编码之前在javascript中检查数组之前如何在PHP中正确构造数组感到困惑。

I'm trying to store an array of objects with their grid reference (x,y) 我正在尝试使用其网格参考(x,y)存储对象数组

So i do this in php: 所以我在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: 然后,在javascript中,我尝试检查给定坐标上是否存在对象,因此我尝试执行以下操作:

 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. sdata是json编码后的数组。

My json encode looks like this: 我的json编码看起来像这样:

 {"44":"0","21":"0"}

Problem is i get : Uncaught SyntaxError: Unexpected token ] on the alert line. 问题是我得到了:警报行上出现Uncaught SyntaxError:Unexpected token]。

Also is my approach correct or is there a better way to construct my array? 我的方法也是正确的还是有更好的方法构造数组?

You have a JavaScript syntax error in your code. 您的代码中存在JavaScript语法错误。 There is an extra ] on your alert() line. alert()行上有一个额外的]

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 . 如果您实际上是试图将值ij连接起来,则还需要使用+而不是. , so you would use i.toString()+j.toString() as the key rather than ij . ,因此您将使用i.toString()+j.toString()作为键而不是ij

Example of using this with two-dimensional arrays: 将其用于二维数组的示例:

PHP 的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 的JavaScript

for(var x in sdata) {
    for(var y in sdata[x]) {
        alert('Object found at coordinates ' + x + ',' + y + ' ' + sdata[x][y]);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM