<div class="widget-box widget-color-blue2">
<div class="col-md-6 col-xs-12">
<canvas id="myChart" width="400" height="400"></canvas>
<?php
$test_arry=array();
$test_arry["Red"]=12;
$test_arry["Blue"]=19;
$test_arry["Yellow"]=3;
$test_arry["Green"]=5;
$test_arry["Purple"]=2;
$test_arry["Orange"]=3;
$t_labels = array_keys( $test_arry );
var_dump($t_labels);
$t_js_labels = graph_strings_array( $t_labels );
var_dump($t_js_labels);
$t_values = array_values( $test_arry );
var_dump($t_values);
$t_js_values = graph_numeric_array( $t_values );
var_dump($t_js_values);
//exit();
?>
<script>
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [<?php echo $t_js_labels;?>],
datasets: [{
label: 'Votes label',
data: [<?php echo $t_js_values; ?>],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</div>
</div>
array (size=6)
0 => string 'Red' (length=3)
1 => string 'Blue' (length=4)
2 => string 'Yellow' (length=6)
3 => string 'Green' (length=5)
4 => string 'Purple' (length=6)
5 => string 'Orange' (length=6)
string '"Red", "Blue", "Yellow", "Green", "Purple", "Orange"' (length=52)
array (size=6)
0 => int 12
1 => int 19
2 => int 3
3 => int 5
4 => int 2
5 => int 3
string '12, 19, 3, 5, 2, 3' (length=18)
/**
* Converts an array of php strings into an array of javascript strings without [].
* @param array $p_strings The array of strings
* @return string The js code for the array without [], e.g. "a", "b", "c"
*/
function graph_strings_array( array $p_strings ) {
$t_js_labels = '';
foreach ( $p_strings as $t_label ) {
if ( $t_js_labels !== '' ) {
$t_js_labels .= ', ';
}
$t_js_labels .= '"' . $t_label . '"';
}
return $t_js_labels;
}
/**
* Converts an array of php numbers into an array of javascript numbers without [].
* @param array $p_values The array of values.
* @return string The js code for the array without [], e.g. 1, 2, 3.
*/
function graph_numeric_array( array $p_values ) {
$t_js_values = '';
foreach( $p_values as $t_value ) {
if ( $t_js_values !== '' ) {
$t_js_values .= ', ';
}
$t_js_values .= $t_value;
}
return $t_js_values;
}