PHP 版本 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;
}
那有意义吗?
假设我有一个 PHP 数组,在print_r($totalData);
调用时看起来像这样:
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]];
为了将 php 数组转换为 javascript 数组,似乎有多种方法,但我尝试过的每一种方法都无法得到所有方括号。我得到的最接近的是:
<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 二维数组到 Javascript 二维数组但没有花括号?我希望远离编写手动填充每个位置的方法?我希望我只是错误地使用了 JSON。任何帮助都会很棒。