Преобразование массива в строку при использовании canvas js в yii2 - PullRequest
0 голосов
/ 17 апреля 2020

Я пытаюсь загрузить график на своей индексной странице в yii2 project. Ниже мой код

<?PHP

$dataPoints1 = array(
array("label"=> "2010", "y"=> 36.12),
array("label"=> "2011", "y"=> 34.87),
array("label"=> "2012", "y"=> 40.30),
array("label"=> "2013", "y"=> 35.30),
array("label"=> "2014", "y"=> 39.50),
array("label"=> "2015", "y"=> 50.82),
array("label"=> "2016", "y"=> 74.70)
);
$dataPoints2 = array(
array("label"=> "2010", "y"=> 64.61),
array("label"=> "2011", "y"=> 70.55),
array("label"=> "2012", "y"=> 72.50),
array("label"=> "2013", "y"=> 81.30),
array("label"=> "2014", "y"=> 63.60),
array("label"=> "2015", "y"=> 69.38),
array("label"=> "2016", "y"=> 98.70)
);
?>

Мой JS

<?PHP
$script = <<< JS
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
theme: "light2",
title:{
    text: "Average Amount Spent on Real and Artificial X-Mas Trees in U.S."
},
legend:{
    cursor: "pointer",
    verticalAlign: "center",
    horizontalAlign: "right",
    itemclick: toggleDataSeries
},
data: [{
    type: "column",
    name: "Real Trees",
    indexLabel: "{y}",
    yValueFormatString: "$#0.##",
    showInLegend: true
    dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?>
},{
    type: "column",
    name: "Artificial Trees",
    indexLabel: "{y}",
    yValueFormatString: "$#0.##",
    showInLegend: true,
    dataPoints: <?php echo json_encode($dataPoints2, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();

function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
    e.dataSeries.visible = false;
}
else{
    e.dataSeries.visible = true;
}
chart.render();
}
}

JS;
$this->registerJs($script);
?>

Когда я запускаю свой код, я получаю ошибку ниже

Преобразование массива в строку

Эта ошибка возникает в dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?>

Как я могу избавиться от этой ошибки? Любая помощь будет высоко ценится

Ответы [ 2 ]

1 голос
/ 18 апреля 2020

Вы должны закодировать массив php в json вне heredo c и передать вывод в часть javascript, и вы не используете теги php, но используете фигурные скобки {} для анализа значения из переменной внутри heredo c.

См. ниже, она должна работать правильно

<?PHP
$dataPoints1 = json_encode($dataPoints1, JSON_NUMERIC_CHECK);
$dataPoints2 = json_encode($dataPoints1, JSON_NUMERIC_CHECK);

$script = <<< JS
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1", {
animationEnabled: true,
theme: "light2",
title:{
    text: "Average Amount Spent on Real and Artificial X-Mas Trees in U.S."
},
legend:{
    cursor: "pointer",
    verticalAlign: "center",
    horizontalAlign: "right",
    itemclick: toggleDataSeries
},
data: [{
    type: "column",
    name: "Real Trees",
    indexLabel: "{y}",
    yValueFormatString: "$#0.##",
    showInLegend: true
    dataPoints: {$dataPoints1}
},{
    type: "column",
    name: "Artificial Trees",
    indexLabel: "{y}",
    yValueFormatString: "$#0.##",
    showInLegend: true,
    dataPoints: {$dataPoints2}
}]
});
chart.render();

function toggleDataSeries(e){
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
    e.dataSeries.visible = false;
}
else{
    e.dataSeries.visible = true;
}
chart.render();
}
}

JS;
$this->registerJs($script);
?>
0 голосов
/ 17 апреля 2020

@ Faisal, вы передаете строку (эхо печатает что-либо как строки) в «dataPoints», но она принимает JSON Array.

Вам необходимо проанализировать строку json, чтобы преобразовать ее в действительный JSON. Используйте функцию JSON .parse () и измените свой код в Javascript, как показано ниже.

dataPoints: JSON .parse ()

Обновлено:

Сначала возьмите dataPoints из PHP в переменной перед инициализацией диаграммы , Затем передайте эту переменную в конфигурации диаграммы. Также попробуйте с JSON .parse ().

Если она все еще не работает, выведите эту новую переменную в Консоль, проверьте вывод и опубликуйте ее здесь

...