将多维smary数组转换为Javascript多维数组

时间:2016-06-14 05:40:40

标签: javascript arrays smarty

我在PHP中有一个名为graph的多维数组,我发送到smarty.tpl文件,我在tpl中以smarty变量图的名义获取它。

Array
(
    [0] => Array
        (
            [weight] => 950.500
            [date] => 27
        )

    [1] => Array
        (
            [weight] => 800.100
            [date] => 31
        )

    [2] => Array
        (
            [weight] => 250.250
            [date] => 03
        )

)

现在,我想在那个tpl中用javascript创建一个多维数组。我怎么能这样做?

echo json_encode($graph);


$smarty -> assign("graph",$graph);
$smarty -> assign("data_weight",$data_weight);

和tpl文件内部我试图以这种格式获取数组

var d1 = [[1,100], [2,110], [3,99],  [4,114]]; 

我试过这个命令将json对象转换为数组

var d1 = JSON.parse(JSON.stringify(graph));

但即使这样也行不通。

1 个答案:

答案 0 :(得分:0)

最简单,最好的方法是将这个数组从php发送到json格式的javascript ...即

您可以将其编码为

echo json_encode($YOUR_PHP_ARRAY);

当你在javascript端收到它时,它总是很好地对待json,所以你可以直接在客户端直接使用它。

当你和我分享你的json_encode时...这里是用来读取你的数组的javascript代码..我用document.write将它打印在你的页面上.. 我保存了你的json javascript将从你的php var x

中收到

    	var x = [{"weight":"950.500","date":"27"},{"weight":"800.100","date":"31"},{"weight":"25‌​0.250","date":"03"}];
    	// console.log(x);
    
    	for(var i = 0;i<x.length;i++){
    		console.log(x[i]);
    		document.write("Weight : "+x[i].weight);
    		document.write("Date : "+x[i].date);
    		document.write("<br/>");
    	}
    

以下是运行代码段时的外观。 enter image description here

使用smarty,您可以像

一样编码
var graph = {$graph|json_encode};

获取图形变量,这是一个javascript变量,如我的代码段所示,遍历。 要查看数组结构,您可以

console.log(graph);

并在浏览器控制台中查看。

相关问题