I have the following three php arrays. Three of them are key value pairs
$needles = ["Needle1", "Needle2", "Needle3", "Needle4", "Needle5"];
$uph1 = ["Needle1" => 3, "Needle3" => 5, "Needle4" => 7];
$uph2 = ["Needle1" => 4, "Needle2" => 2, "Needle3" => 4];
$uph3 = ["Needle1" => 4, "Needle2" => 5, "Needle3" => 7, "Needle4" => 2];
$numberOfItems is the total number of items in the $needles array which is 5
I am trying to plot this using google charts as below
The following is loading google charts
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
The following is the div that shows chart
<div id="chart_div" style="width: 900px; height: 500px;"></div>
The following is populating chart
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
// Some raw data (not necessarily accurate)
var data = google.visualization.arrayToDataTable([
['Needle', 'One', 'Two', 'Three'],
<?php
for($i=0; $i<$numberOfItems; $i++){
if(array_key_exists($needles[$i],$uph1) || array_key_exists($needles[$i],$uph2) || array_key_exists($needles[$i],$uph3)){
if($i != ($numberOfItems-1)){
// echo '["'.$needles[$i].'", 2, 4, 6],'; //This is working
echo '["'.$needles[$i].'", '.$uph1[$needles[$i]].', '.$uph2[$needles[$i]].', '.$uph3[$needles[$i]].'],'; //This is not working
}else{
// echo '["'.$needles[$i].'", '.$uph1[$needles[$i]].', '.$uph2[$needles[$i]].', '.$uph3[$needles[$i]].']';
}
}
}
?>
]);
var options = {
title: 'Average UPH Per Month',
vAxis: {
title: 'Avg UPH'
},
hAxis: {
title: 'Needle Type'
},
seriesType: 'bars',
series: {
3: {
type: 'line'
}
}
};
var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
As you can see my comments in the code above, when I try to echo the array ($uph1, $uph2, $uph3) values using the key ($needles[$i]), it is not working. I having Uncaught SyntaxError: Unexpected token '<' error in my console. I used some static values instead of using the above mentioned arrays, it is working fine.
Does anyone know what am I doing wrong here?
** Edit 1 **
I solved it adding the following if condition before the if($i != ($numberOfItems-1)){ }
if(array_key_exists($needles[$i],$uph1)){
$uph1Avg = $uph1[$needles[$i]];
}else{
$uph1Avg = 0;
}
if(array_key_exists($needles[$i],$uph2)){
$uph2Avg = $uph2[$needles[$i]];
}else{
$uph2Avg = 0;
}
if(array_key_exists($needles[$i],$uph3)){
$uph3Avg = $uph3[$needles[$i]];
}else{
$uph3Avg = 0;
}
Issue was due to some of the keys don't exist in the key value arrays $uphx. Because the main if condition is checking if key exist or not in any one of the $uphx array. So if any one key exist, it will go into if block. But please remember that some of the keys may not present in some of the $uphx arrays.
