将字符串编码为json [英] Encoding string to json

查看:108
本文介绍了将字符串编码为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编码字符串给json有问题。我正在做一个谷歌饼图。图表将充满来自数据库的数据。 Google图表需要json格式的数据。

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.

下面是一个字符串应该如何显示的例子。现在我有一个动态组装字符串与数据库中的数据的问题。
JSON_encode是不够的,它必须像这样的字符串格式和行格式!
请帮助。

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;


 ?>


推荐答案

我猜你的问题不知道如何从一个PHP对象中生成这样一个JS对象。
您需要创建一个PHP数组,然后使用json_encode函数:

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);

这篇关于将字符串编码为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆