如何解析数据并将其传递到我的 Morris.js 图表

How to parse and pass data to my Morris.js chart

我想在我的应用程序中使用莫里斯图表来显示一些数据。首先,让我向您展示我的 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 文件中的一个片段。此代码有效。但是现在我想从我的数据库中添加数据。

我看到了不同的方法,但似乎对我没有任何作用。 dd 数据如下所示:

array:2 [▼
  1 => array:2 [▼
    "name" => "Store 1"
    "value" => 25
  ]
  2 => array:2 [▼
    "name" => "Store 2"
    "value" => 75
  ]

]

我需要如何解析这些数据?以及如何将它附加到我的图表,因为我不能在 js 文件中执行 blade 语法 style/php。

谢谢, 鲁马


编辑

我有更新!你的回答对我帮助很大,但我仍然有一个小问题。我知道这个问题,但不知道为什么会这样。

让我们来看看这个示例数据:

$data = [
    [
        "label" => "Store 1",
        "value" => "75"
    ],
    [
        "label" => "Store 2",
        "value" => "25"
    ],
];

DD'ed wit 将如下所示:

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。

您可以使用 array_map 将其转换为正确的格式,并在加载 handleStoreIncomeShareDonutChart 文件之前将其作为变量输出到 <script> 中。以下代码应适用于 PHP 5.3 及更高版本。

$data = array(
  array(
    'name' => 'Store 1',
    'value' => 25,
  ),
  array(
    'name' => 'Store 2',
    'value' => 75,
  ),
);

$output = array_map(function ($record) {
  return array(
    'label' => $record['name'],
    'value' => $record['value'],
  );
}, $data);
echo '<script>var morris_data = ' . json_encode($output) . ';';