【发布时间】:2015-08-11 10:28:44
【问题描述】:
我想在我的应用程序中使用莫里斯图来显示一些数据。首先,让我向您展示我的js:
var handleStoreIncomeShareDonutChart = function() {
var green = '#00acac';
var blue = '#348fe2';
Morris.Donut({
element: 'storeincomeshare-donut-chart',
data: [
{label: "Store 1", value: 69},
{label: "Store 2", value: 31}
],
colors: [green, blue],
labelFamily: 'Open Sans',
labelColor: 'rgba(255,255,255,0.4)',
labelTextSize: '12px',
backgroundColor: '#242a30'
});
};
这是我的 charts.js 文件中的一个 sn-p。此代码有效。但现在我想从我的数据库中添加数据。
我在这方面看到了不同的方法,但似乎没有什么对我有用。 dd'ed 数据如下所示:
array:2 [▼
1 => array:2 [▼
"name" => "Store 1"
"value" => 25
]
2 => array:2 [▼
"name" => "Store 2"
"value" => 75
]
]
我需要如何解析这些数据?以及如何将其附加到我的图表中,因为我无法在 js 文件中执行刀片语法样式/php。
谢谢, 鲁马
编辑
我有更新!您的回答对我帮助很大,但我仍然有一个小问题。我知道问题所在,但不知道为什么会这样。
让我们来看看这个样本数据:
$data = [
[
"label" => "Store 1",
"value" => "75"
],
[
"label" => "Store 2",
"value" => "25"
],
];
DD 的机智将如下所示:
array:2 [▼
0 => array:2 [▼
"label" => "Store 1"
"value" => "75"
]
1 => array:2 [▼
"label" => "Store 2"
"value" => "25"
]
]
执行json_encode($data) 和 dd 结果将如下所示:
"[{"label":"Store 1","value":"75"},{"label":"Store 2","value":"25"}]"
或格式化:
[
{
"label": "Store 1",
"value": "75"
},
{
"label": "Store 2",
"value": "25"
}
]
这是有效的 JSON,适用于 morris.js 图表。但是,当我对 db 中的数据执行相同操作时,会发生一些有趣的事情。
DD 看起来像这样:
array:2 [▼
1 => array:2 [▼
"label" => "Store 1"
"value" => 75
]
2 => array:2 [▼
"label" => "Store 2"
"value" => 25
]
]
而json_encode() 不会像上面那样对其进行编码:
{
"1": {
"label": "Studio Friedberg",
"value": 0
},
"2": {
"label": "Studio Klein-Auheim",
"value": 0
}
}
这也是有效的 JSON,但不被 morris.js 图表接受。 我花了一些时间才弄清楚为什么会发生这种情况。你看不出这么好的区别,让我们来看看这两张图:
那么我的问题是什么?我有一个 foreach 循环,在其中我将数组键设置为商店的 id。
【问题讨论】:
标签: javascript php laravel blade morris.js