Search code examples
phparraysgoogle-visualization

PHP stdObject to array that can be used in Google Charts


I would like to use google charts to visualize some data.

I know from documentation that in order to use google charts the data must be in the following form:

[["C1","C2","C3],[C1V1,C2V1,C3V1],[C1V2,C2V2,C3V3]]

Where c1-c3 are columns one to three and the same of v1-v3 for values.

I currently have data from a query in php in the following form:

Array ( [0] => stdClass Object ( [C1] => C1V1 [C2] => C2V1 [C3] => C3V3 ))

I am getting my data using a simple sql query in laravel:

 $live = DB::connection('azure')->select("SELECT C1,C2 FROM tableName");

How can I convert from my data form to the one from the top so that I can use google charts.

I am using PHP so I would like to be able to convert it in that language.

Any help is greatly appreciated!


Solution

  • To format the data in source array $arr to fit your needs, you could use:

    <?php
    $i=0;
    $newArr[0] = array_keys($arr[0]);
    foreach($arr as $record) {
        $i++;
        foreach($record as $col => $val) {
            $newArr[$i][] = $val;
        }
    }
    

    working demo