Php/ajax return JSON 与 javascript 数组的形式相同

Php/ajax return JSON in same form as javascript array

我正在使用 charts.js 插件来创建图表。它使用 javascript 数组 data 来生成图表。

var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.2)",
            strokeColor: "rgba(220,220,220,1)",
            pointColor: "rgba(220,220,220,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
        {
            label: "My Second dataset",
            fillColor: "rgba(151,187,205,0.2)",
            strokeColor: "rgba(151,187,205,1)",
            pointColor: "rgba(151,187,205,1)",
            pointStrokeColor: "#fff",
            pointHighlightFill: "#fff",
            pointHighlightStroke: "rgba(151,187,205,1)",
            data: [28, 48, 40, 19, 86, 27, 90]
        }
    ]
};

我想在不同的时间范围内使用 ajax 到 return 结果。 我如何使用 php 生成响应,以便当我在 ajax 成功读取它时,我可以像使用 var data 生成初始图表一样使用它。

        $.ajax('/chart.php', {
            type: 'POST',
            data: {range: range},
            dataType: 'json',
            success: function(data) {
                console.log(data);
            }
        });

你想要的是创建一个对象数组,然后使用 json_encode 它应该会产生你需要的东西。试试这个:

$array = array();
$dataset = new stdClass;
$dataset->label = "My first dataset";
// repeat for each field
$array[] = $dataset;
echo json_encode($array);

我们可以做的是缩短这个时间,而不是每次我们可以 use an array and typecast it to an object 像这样声明一个新数据集:

$datasets = array();
$datasets[] = (object) array(
    'label' => "My First dataset",
    'fillColor' => "rgba(220,220,220,0.2)",
    'strokeColor' => "rgba(220,220,220,1)",
    'pointColor' => "rgba(220,220,220,1)",
    'pointStrokeColor' => "#fff",
    'pointHighlightFill' => "#fff",
    'pointHighlightStroke' => "rgba(220,220,220,1)",
    'data' => [65, 59, 80, 81, 56, 55, 40]
);

Check out this eval.in 一个工作示例。

更新

要获得完整的结构,您需要:

$data = (object) [
    'labels' => ["January", "February", "March", "April", "May", "June", "July"],
    datasets => []
];

$data->datasets[] = (object) [
    'label' => "My First dataset",
    'fillColor' => "rgba(220,220,220,0.2)",
    'strokeColor' => "rgba(220,220,220,1)",
    'pointColor' => "rgba(220,220,220,1)",
    'pointStrokeColor' => "#fff",
    'pointHighlightFill' => "#fff",
    'pointHighlightStroke' => "rgba(220,220,220,1)",
    'data' => [65, 59, 80, 81, 56, 55, 40]
];

echo json_encode($data);