Search code examples
javascriptphphtmlgoogle-visualization

Google chart and php arrays


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.


Solution

  • You can push your array value inside javascript array and then pass this to your google chart . So, use below code :

    <script>
    var arrays = [['Needle', 'One', 'Two', 'Three']] //your intial column..
    var dummy = [] //declare this
     <?php
          for($i=0; $i<count($needles); $i++){ ?>
            dummy.push('<?php echo $needles[$i]; ?>',<?php echo (array_key_exists($needles[$i],$uph1)) ? $uph1[$needles[$i]] : 0 ; ?>,<?php echo (array_key_exists($needles[$i],$uph2)) ? $uph2[$needles[$i]] : 0 ; ?>,<?php echo (array_key_exists($needles[$i],$uph3)) ? $uph3[$needles[$i]] : 0 ; ?>)  
            arrays.push(dummy)//push value inside main array
            dummy =[] //clear all value
     <?php }
      ?>
    google.charts.load('current', {
      'packages': ['corechart']
    });
    google.charts.setOnLoadCallback(drawVisualization);
    
    function drawVisualization() {
    
      var data = google.visualization.arrayToDataTable(
        arrays); //pass it here
    
      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);
    }
    </script>
    

    Output :

    enter image description here