PHP stdObject to array that can be used in Google Charts

Viewed 67

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!

2 Answers

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

You need to create the first inner array using the indexes returned from the DB. So if your database query returns an associative array you can use the array_keys function to get an array of all the keys, add that as the first entry in the your main array, then loop through your data returned from the database and add each row as a new entry in your main array.

Related