0

I use Chart.js to present my data.

var data_2 = {
    datasets: [{
        data: //print php var here,
        backgroundColor: [
            '#00c0ef',
            '#f56954',
            '#00a65a',
        ],
    }],
};

I want to change my array format from something like

Array ( [jml] => 833 ) Array ( [jml] => 6 ) Array ( [jml] => 18 ))

to [833, 6, 18]

My questions are how to print my php variable inside javascript and how to change php's array style to javascript's array style. Thanks

2
  • Assuming $arr = [833, 6, 18] you can do data: <?= json_encode($arr) ?>, Commented Nov 7, 2018 at 4:07
  • 1
    You have 3 arrays not 1, poss dupe: How to get an array of specific “key” Commented Nov 7, 2018 at 4:09

3 Answers 3

1

json_encode() is well suited for injecting data into JavaScript:

<?php
$data = [["jml"=>833], ["jml"=>6], ["jml"=>18]];
$arr = array_column($data, "jml");
$var = json_encode($arr);
?>

<script>
var data_2 = {
    datasets: [{
        data: <?= $var ?>,
        backgroundColor: [
            '#00c0ef',
            '#f56954',
            '#00a65a',
        ],
    }],
};
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

In php part:

<?php
$dataArr = Array ( Array ( 'jml' => 833 ), Array ( 'jml' => 6 ), Array ( 'jml' => 18 ));

$chartData = '';
foreach($dataArr as $data){
    $chartData .= $data['jml'].',';
}

$chart = '['.rtrim($chartData,',').']';
?>

Then change in your script to:

var data_2 = {
    datasets: [{
        data: <?php  echo $chart; ?>,
        backgroundColor: [
            '#00c0ef',
            '#f56954',
            '#00a65a',
        ],
    }],
};

Comments

0

Simple way
I had already tired this way,its working.See this link but,I have use laravel Recurring events in FullCalendar with Laravel

var data_2 = {
    datasets: [{
        data: [<?php echo $var[0],$var[1],$var[2] ?>],
        backgroundColor: [
            '#00c0ef',
            '#f56954',
            '#00a65a',
        ],
    }],
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.