Alberto Méndez
Alberto Méndez

Reputation: 1064

Draw a Google Chart with undefined number of lines

I need to draw a Google Chart with an undefined number of lines (rows). Lets suppose I need to draw the number of goals of two teams in a certain day (the number of teams is fixed for the example, but it could be anyone, the number of days are the same for all teams). I have this array:

Array
(
    [team1] => Array
        (
            [0] => Array
                (
                    [day] => 1
                    [goals] => 3
                )

            [1] => Array
                (
                    [day] => 2
                    [goals] => 1
                )

            [2] => Array
                (
                    [day] => 3
                    [goals] => 0
                )
        )
    [team2] => Array
        (
            [0] => Array
                (
                    [day] => 1
                    [goals] => 1
                )

            [1] => Array
                (
                    [day] => 2
                    [goals] => 2
                )

            [2] => Array
                (
                    [day] => 3
                    [goals] => 4
                )
        )
)

I have tried creating this loop:

    $resultArray = array();
    $resultArray['cols'][] = array('label' => "Day", 'type' => 'string');
    // $array is the one shown before
    foreach($array as $key => $chartData){
        $resultArray['cols'][] = array('label' => $key, 'type' => 'number');
        foreach($chartData as $data){
            $resultArray['rows'][] = array('c' => array( array('v' => $data['day']), array('v' => $data['goals'])));
       }
   }

The problem is that the chart only draws one line with the data from both teams joined all together instead two lines one for each team.

I would really appreciate any help.

Upvotes: 0

Views: 78

Answers (1)

M31
M31

Reputation: 1418

I think your making it harder on yourself using associative arrays for google chart data. The data structure of your array is also adding some challenges to the loop making it a bit more challenging to get the data out in the desired format:

$chartData = array();
$chartData[] = array("Day");
foreach($array as $key => $a){
  $chartData[0][] = $key;
  for($i = 0; $i < count($a); $i++){
    if(!is_array($chartData[$i+1])){ 
      $chartData[$i+1] = array(); 
      $chartData[$i+1][] = $a[$i]['day'];
    }
    $chartData[$i+1][count($chartData[0])-1] = $a[$i]['goals'];
  }
}

This should give you the format you need to have the desired chart data table:

[
  ["Day","team1","team2"]
  [1,3,1]
  [2,1,2]
  [3,0,4]
]

Creating a line for the number of goals (y Axis) for each team over the number of days (x axis). Hope this helps

Upvotes: 1

Related Questions