我正在尝试使用php pdo的非弃用技术转换通过以下代码获得的数组:

$stm = $conn->prepare("SELECT * FROM mysqltable");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
print_r($results);

使用FusionCharts所需的以下格式
[
{
label: "CJ Anderson",
value: "25"
},
{
label: "Imran Tahir",
value: "25"
},
...
...
]

原始数组如下:
Array (
    [0] => Array (
        [Id] => 6
        [Number] => 1234567890
        [Visits] => 1
        [Name] => John
    )
    [1] => Array (
        [Id] => 7
        [Number] => 1236549871
        [Visits] => 9
        [Name] => Jerry
    )
    [2] => Array (
        [Id] => 8
        [Number] => 2147483647
        [Visits] => 3
        [Name] => Jane
    )
)

任何帮助都将不胜感激,谢谢。
编辑:
正如我在下面评论的。我有一个完整的php文件,如果你手动输入数据的话。不过,当我把$jsonencodeddata放进去时,我无法让它工作。思想?
<html>
   <head>
    <title>FusionCharts XT - Column 2D Chart - Data from a database</title>
    <link  rel="stylesheet" type="text/css" href="css/style.css" />

    <!-- You need to include the following JS file to render the chart.
    When you make your own charts, make sure that the path to this JS file is correct.
    Else, you will get JavaScript errors. -->

    <script src="fusioncharts/js/fusioncharts.js"></script>
  </head>

   <body>
 <?php

 try {

# MySQL with PDO_MYSQL
$mysql_host = 'host';
$mysql_database = 'table';
$mysql_username = 'user';
$mysql_password = 'pass';

    $conn = new PDO("mysql:host=$mysql_host; dbname=$mysql_database", $mysql_username, $mysql_password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8

}
catch(PDOException $e) {
echo $e->getMessage();
}

        // Form the SQL query that returns the top 10 most populous countries

        // Execute the query, or else return the error message.
$stm = $conn->prepare("SELECT Name, Visits FROM mysqltable"); //WHERE Area :SelArea");
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);

 include("fusioncharts.php");

$jsnarray = array();
foreach($results as $k => $v){
    $jsnarray[] = array('label' => $results[$k]['Name'], 'value' => $results[$k]['Visits']);
};
    $jsonEncodedData=json_encode($jsnarray);

    new FusionCharts("type of chart",
            "unique chart id",
            "width of chart",
            "height of chart",
            "div id to render the chart",
            "type of data",
            "actual data");
    $columnChart = new FusionCharts(
            "column2d",
            "ex1" ,
            "600",
            "400",
            "chart-1",
            "json",
            '{
               "chart":
               {
                  "caption":"Harry\'s SuperMart",
                  "subCaption":"Top 5 stores in last month by revenue",
                  "numberPrefix":"$",
                  "theme":"ocean"
               },
               "data":  //$jsonEncodedData}'); <---I tried to insert this after "data":but no results unlike if you put raw data**
               [
                  {
                     "label":"Bakersfield Central",
                     "value":"880000"
                  },
                  {
                     "label":"Garden Groove harbour",
                     "value":"730000"
                  },
                  {
                     "label":"Los Angeles Topanga",
                     "value":"590000"
                  },
                  {
                     "label":"Compton-Rancho Dom",
                     "value":"520000"
                  },
                  {
                     "label":"Daly City Serramonte",
                     "value":"330000"
                  }
               ]
        }');
    // Render the chart
    $columnChart->render();
?>

    <div id="chart-1"><!-- Fusion Charts will render here--></div>

   </body>

</html>

=15年12月28日编辑==========
在没有结果的情况下尝试了下面的代码,我的问题是我们不应该以“}”结尾,因为他们要求这样做:
    $columnChart = new FusionCharts(
            "column2d",
            "ex1" ,
            "600",
            "400",
            "chart-1",
            "json",
            '{
               "chart":
               {
                  "caption":"Harry\'s SuperMart",
                  "subCaption":"Top 5 stores in last month by revenue",
                  "numberPrefix":"$",
                  "theme":"ocean"
               },
               "data": ' . $jsonEncodedData);
               //}';
    // Render the chart
    print_r($columnChart);
    $columnChart->render();
?>

    <div id="chart-1"><!-- Fusion Charts will render here--></div>

   </body>

</html>

我还想发布“manual”方法和“fetch”方法之间的数组差异(在本次编辑中如上)。
使用FETCH:
FusionCharts对象([ConstructorOptions:FusionCharts:Private]=>数组(>[Type]=>Column2D[ID]=>Ex1[Width]=>600[Height]=>400[Renderat]=>>Chart-1[DataFormat]=>JSON[DataSource]=>{“Chart”:{>“Caption”:“Harry's Supermart”,“SubCaption”:“上个月的前5个存储按>Revenue“,”numberPrefix“:”$“,“theme”:“ocean”},“data”:>[{“label”:“john”,“value”:“125”},{“label”:“jerry”,“value”:“125”},{“label”:“jane”,“value”:“125”}])[constructorTemplate:fusionCharts:private]=>[renderTemplate:fusionCharts:private]=>)
使用手动方法(有效):
FusionCharts对象([ConstructorOptions:FusionCharts:Private]=>数组(>[Type]=>Column2D[ID]=>Ex1[Width]=>600[Height]=>400[Renderat]=>>Chart-1[DataFormat]=>JSON[DataSource]=>{“Chart”:{>“Caption”:“Harry's Supermart”,“SubCaption”:“上个月的前5个存储按>Revenue“,”NumberPrefix:“$”,“Theme”:“Ocean”},“Data”:[{>“Label”:“Bakersfield Central”,“Value”:“880000”},{“Label”:“Garden Groove>Harbour”,“Value”:“730000”},{“Label”:“Los Angeles Topanga”,“Value”:“590000”},{“Label”:“Compton Rancho Dom”,“Value”:“520000”},{>“Label”:“Daly City Serramonte”,“value”:“330000”})>[constructoremplate:fusioncharts:private]=>[rendertemplate:fusioncharts:private]=>)
我马上看到了两个区别,手册在“data”和ending}参数周围插入了空格。

最佳答案

有一种自动(而且简单得多)的方法:

$stm = $conn->prepare('SELECT Name AS label, Visits AS value FROM mysqltable;');
$stm->execute();
$results = $stm->fetchAll(PDO::FETCH_ASSOC);
$jsonEncodedData = json_encode($results);
echo $jsonEncodedData;

输出(本地测试):
[{"label":"Foo","value":"5"},{"label":"Bar","value":"15"}]

这样你就可以这样使用它:
$columnChart = new FusionCharts('...
...
"data": ' . $jsonEncodedData . '}');

注意最后的. '}'
编辑前:
你可以这样做:
// This part is just for running purposes
$foo = array (
    0 => Array (
        'Id' => 6,
        'Number' => 1234567890,
        'Visits' => 1,
        'Name' => 'John'
    ),
    1 => array (
        'Id' => 7,
        'Number' => 1236549871,
        'Visits' => 9,
        'Name' => 'Jerry'
    ),
    2 => array (
        'Id' => 8,
        'Number' => 2147483647,
        'Visits' => "3", // Example to output quoted
        'Name' => 'Jane'
    )
);

$bar = array();
foreach($foo as $k => $v){
    $bar[] = array('label' => $foo[$k]['Name'], 'value' => $foo[$k]['Visits']);
}

echo json_encode($bar);

输出:
[{"label":"John","value":1},{"label":"Jerry","value":9},{"label":"Jane","value":"3"}]

在一行中与你的(来自问题)进行比较:
[{label: "CJ Anderson",value: "25"},{label: "Imran Tahir",value: "25"},...]

注:我假设valueVisit表示,labelName表示。
阅读有关json_encode的更多信息。

09-28 05:28