2

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。任何帮助都会很棒。

4

2 回答 2

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);

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

于 2012-09-25T18:45:44.570 回答
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>
于 2012-09-26T07:28:09.443 回答