0

I' ve got a problem with encoding string to json. I'm doing a google pie chart. Chart will be filled with data from database. Google chart requires data in json format.

Below is the example of a string how it supposed to look like. Now I have a problem with dynamically "assembling" the string with data from database. JSON_encode is not enough, it has to be in format like this string with cols and rows! Please help.

<?php 

 $db=new DB();
 $db->connect();
 $db->selectBase();

 $rows = array();
 $sth=$db->st_glede_na_tip() or die(mysql_error());
 while($r = mysql_fetch_assoc($sth)) {
     $rows[] = $r;
}


 $string= '{
     "cols": [
        {"id":"","label":"Content","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
       ],
    "rows": [
        {"c":[{"v":"Books"},{"v":3}]},
        {"c":[{"v":"Video"},{"v":1}]},
        {"c":[{"v":"Audio"},{"v":1}]},
        {"c":[{"v":"Movie"},{"v":1}]},
      ]
   }';

   echo $string;


 ?>
4
  • 1
    you could use json_encode() function...? Commented Jul 16, 2012 at 8:12
  • 1
    Whats wrong with json_encode ??? Commented Jul 16, 2012 at 8:12
  • Google charts requires unique format with cols and rows. Commented Jul 16, 2012 at 8:14
  • 1
    json_encode can encode any PHP data structure to the equivalent JSON/Javascript data structure. Your "special cols and rows" format is just a nested JSON array. You can create the same array structure using a PHP array, then json_encode that. Commented Jul 16, 2012 at 8:18

1 Answer 1

5

I'm guessing your problem is not knowing how to generate such a JS object from a PHP object. You need to create a PHP array as such and then use the json_encode function :

$data = array(
    'cols' => array(
        array('id' => '', 'label' => 'Content', 'pattern' => '', 'type' => 'string'),
        array('id' => '', 'label' => 'Slices', 'pattern' => '', 'type' => 'number')     
    ),
    'rows' => array(
        array('c' => array(
            array('v' => 'Books'),
            array('v' => 3)         
        )), 
        array('c' => array(
            array('v' => 'Video'),
            array('v' => 1)         
        )),     
        array('c' => array(
            array('v' => 'Audio'),
            array('v' => 1)         
        )),     
        array('c' => array(
            array('v' => 'Movie'),
            array('v' => 1)         
        ))      
    )   
);  

echo json_encode($data);
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for that. But how would I get data from database into that array?
i don't know your database structure so that's an entirely different matter and it's yours!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.