php - 我如何动态创建多维javascript数组

标签 php javascript arrays multidimensional-array

我正在尝试动态构建一个javascript数组,其中_tags是一个全局定义的数组,然后通过ajax请求将其发送到php。基本上我需要 uid 作为键,x,y 作为子数组。在 php 中它看起来像这样

$arr[$uid] = array('x'=>$x,'y'=>$y); 

但是我在 javascript 中无法找出这样的数组,这就是我所拥有的

function add_tag_queue(uid,x,y){

    var arr = new Array(3);
    arr[0] = uid;
    arr[1] = x;
    arr[2] = y;

    _tags.push(arr);
}

最佳答案

This works ok as long as their is only one entry being added to the array, I'm adding multiple values, in other words the function will run a few times and then i want to send that entire array, but this seems to just be adding everything with a comma delimeter.

我不确定你在这里到底在说什么。我之前给出的第二个示例假设每个 uid 都有一个 x,y 对,但对 _tags 中有多少个 uid 没有限制>。这就是为什么 var _tags = {}; 位于函数的我们这边 - 所以它是一个全局变量。

以下修改将允许您为每个 uid 拥有多个 x,y 对:

function add_tag_queue(uid,x,y){

   /* 
    * detect if _tags[uid] already exists with one or more values 
    * we assume if its not undefined then the value is an array... 
    * this is similar to doing isset($_tags[$uid]) in php
    */
   if(typeof _tags[uid] == 'undefined'){
     /* 
      * use an array literal by enclosing the value in [], 
      * this makes _tags[uid] and array with eah element of 
      * that array being a hash with an x and y value
      */
     _tags[uid] = [{'x':x,'y':y}]; 
   } else {
     // if _tags[uid] is already defined push the new x,y onto it
     _tags[uid].push({'x':x, 'y':y});
   }
}

这应该有效:

function add_tag_queue(uid,x,y){

    _tags.push([uid, x,y]);
}

如果您想要uid作为键,那么您需要使用对象/哈希而不是数组

var _tags = {}; // tags is an object
function add_tag_queue(uid,x,y){

        _tags[uid] = {'x':x,'y':y};
    }

关于php - 我如何动态创建多维javascript数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4342023/

相关文章:

php - MySQLi 排名脚本

php - 如何检测 AJAX 中的错误?

javascript - JQuery css 函数不保留其更改

javascript - 转换数组中的输入值

javascript - 如何将对象数组文件访问到 react 组件中?

php - Yii如何美化 Assets URL?

php - PHP 中带有 if 条件的双 foreach

php - 有没有办法使用 zend 创建电子商务网站?

javascript - 在 React Native 中,如何定位和滑动大于屏幕 View 的元素?

Javascript:排序多维数组