Php 格式化JSON数据,以便将其正确传递给Google图表引擎

Php 格式化JSON数据,以便将其正确传递给Google图表引擎,php,json,google-visualization,Php,Json,Google Visualization,我试图建立一个非常简单的表格: Sex % M 40 F 60 使用php对数组进行编码,但假设输入数据错误,则不会绘制任何图形。你能告诉我问题出在哪里吗 $table = array(); $table['cols'] = array( array('label' => 'Sesso', 'type' => 'string'), array('label' => 'Quantita', 'type' => 'number')); $rows = arr

我试图建立一个非常简单的表格:

Sex  %
M    40
F    60
使用php对数组进行编码,但假设输入数据错误,则不会绘制任何图形。你能告诉我问题出在哪里吗

$table = array();
$table['cols'] = array(
array('label' => 'Sesso', 'type' => 'string'),
array('label' => 'Quantita', 'type' => 'number'));

$rows = array();
$temp = array();
$temp[] = array('v' => 'M'); 
$temp[] = array('v' => 60); 
$rows[] = array('c' => $temp);
$temp = array();
$temp[] = array('v' => 'F'); 
$temp[] = array('v' => 40); 
$rows[] = array('c' => $temp);

$table['rows'] = $rows;
$jsonTable = json_encode($table);

如果您尝试以下操作,会发生什么情况:

$table = array(
   'cols' => array(
      array(
         'id' => '1',
         'label' => 'Sesso',
         'type' => 'string'
      ),
      array(
         'id' => '2',
         'label' => 'Quantita',
         'type' => 'number'
      )
   ),
   'rows' => array(
      array(
         'c' => array(
            array(
               'v' => 'M',
               'f' => 60
            )
         )
      ),
      array(
         'c' => array(
            array(
               'v' => 'F',
               'f' => 40
            )
         )
      )
   )
);

$json = json_encode($table);
在他们的文档中查看谷歌的。您应该针对的JSON结构是:

{
  "cols": [
        {"id":"","label":"Topping","pattern":"","type":"string"},
        {"id":"","label":"Slices","pattern":"","type":"number"}
      ],
  "rows": [
        {"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
        {"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
        {"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
      ]
}
这就是我所做的:

    $table = array(
        'cols' => array(
            array( 'id' => '', 'label' => 'Sesso', 'pattern' => '', 'type' => 'string' ),
            array( 'id' => '', 'label' => '#', 'pattern' => '', 'type' => 'number' )
        ),
        'rows' => array(
            array( 'c' => array( array( 'v' => 'Uomini', 'f' => null ), array('v' => 60, 'f' => null) ) ),
            array( 'c' => array( array( 'v' => 'Donne', 'f' => null ), array('v' => 40, 'f' => null) ) )
        )
    );

差不多了,请检查我的答案:)