从PHP数组转到Javascript数组花括号与方括号

时间:2012-09-25 17:52:32

标签: php javascript html ajax json

PHP Version 5.3.14

声明我的数组以及我如何在我的程序中使用它:(改为通用代码方案)

我正在创建这样的PHP数组:

$totalData;

getnumSends($SomeObject){

   $dataArray[0] = $someObject->Date //Date is a String
   foreach($anotherObject as $Object2){
    switch($anotherObject->String){
    case "XX":
        $dataArray[1]+=1;
         break;
    case "YY":
        $dataArray[2]+=1;
        break;
    }
  }
}

   //Method just puts an int value at certain places in the array
   //extra code for putting ints in the array

   return $dataArray;
}
$someIndex = 0;
foreach($someObject as $Object1){ //that is very abstract
   $totalData[$someIndex] = $Object1->getNumSend($someObject);  
   $someIndex+=1;

} 

这有意义吗?

假设我在调用print_r($totalData);时有一个看起来像这样的PHP数组:

Array
(
    [0] => Array
        (
            [0] => 2012-04-25
            [1] => 2
            [2] => 1
            [3] => 2
            [4] => 1
            [5] => 1
            [6] => 1
        )

    [1] => Array
        (
            [0] => 2012-04-29
            [1] => 4
            [2] => 4
            [3] => 2
            [4] => 1
            [5] => 1
        )
)

现在,我有一些我想用来绘制数据的JavaScript代码。脚本需要这种格式的数据:

var matrix = [[2012-04-25, 2, 1, 2, 1, 1, 1], [2012-4-29, 4, 4, 2, 1, 1]];

为了获得一个javascript数组的php数组似乎有多种方式,但我试过的每一种方法都无法得到所有的方括号。我得到的最近的是:

<script>

var matrix = <?php echo json_encode($totalData); ?>;

</script>

从“查看页面来源”输出:

var matrix = [[{"0":"2012-04-25","1":2,"2":1,"3":2,"4":1,"5":1,"6":1}],[{"0":"2012-04-29","1":4,"2":4,"3":2,"4":1,"5":1}]];

有没有办法从PHP 2维数组转到Javascript 2维数组,但没有花括号?我希望远离编写一种手工填充每个点的方法?我希望我只是错误地使用JSON。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

从另一端攻击这个:

我知道你说你不想手动重建数组,但这是一种做到最后的方法:

var matrix = [{"0":"2012-04-25","1":2,"2":1,"3":2,"4":1,"5":1,"6":1},{"0":"2012-04-29","1":4,"2":4,"3":2,"4":1,"5":1}];

var retArray = new Array();
var tmpArr1 = new Array();
var tmpArr2 = new Array();

for(var i = 0; i < retArray.length; ++i) {
    for(property in matrix[i]) {
        (i === 0) ? tmpArr1.push(matrix[i][property]) : tmpArr2.push(matrix[i][property]);
    }
}

retArray.push(tmpArr1);
retArray.push(tmpArr2);

它可能会被清理/变得更抽象,但这是一般方法。

答案 1 :(得分:0)

一种可能的,但不是非常“干净”的方法是方便地破坏阵列

function getJSArray($data){
    $jsMatrix = '[';
    foreach($data as $key => $val){
        $jsMatrix .= '[' . implode(', ', $val) . ']';
        if($key != count($data)-1)
            $jsMatrix .= ', ';
    }
    $jsMatrix .= ']';
    return $jsMatrix;
}

然后

<script>
    var matrix = <?php echo getJSArray($totalData); ?>;
</script>

使用类似

的数组
$data = array(array('2012-04-25', 2, 1, 2, 1, 1, 1),
              array('2012-04-29', 4, 4, 2, 1, 1)
             );

你会得到输出

<script>
    var matrix = [[2012-04-25, 2, 1, 2, 1, 1, 1], [2012-04-29, 4, 4, 2, 1, 1]]
</script>