PHP PDO将数组转换为不同的格式

时间:2015-12-28 04:16:18

标签: php mysql arrays pdo fusioncharts

我试图使用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>

==============编辑12/28/15 ==========

尝试了以下代码但没有结果,问题我不应该结束&#34;}&#34;因为他们需要:

    $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>

我想在&#34;手册&#34;之间发布数组差异。方法和&#34; fetch方法(在此编辑中上面)。

使用fetch:

  

FusionCharts对象([constructorOptions:FusionCharts:private] =&gt;数组(&gt; [type] =&gt; column2d [id] =&gt; ex1 [宽度] =&gt; 600 [高度] =&gt; 400 [renderAt ] =&gt;&gt; chart-1 [dataFormat] =&gt; json [dataSource] =&gt; {&#34;图表&#34;:{&gt;&#34;标题&#34;:&#34; Harry&# 39; s SuperMart&#34;,&#34; subCaption&#34;:&#34;上个月排名前5位的商店&gt;收入&#34;,&#34; numberPrefix&#34;:&#34; $& #34;,&#34;主题&#34;:&#34;海洋&#34;},&#34;数据&#34;:&gt; [{&#34;标签&#34;:&#34; John& #34;&#34;值&#34;:&#34; 125&#34;},{&#34;标签&#34;:&#34;杰里&#34;&#34;值&#34; :&#34; 125&#34;},{&#34;标签&#34;:&#34;简&#34;,&#34;价值&#34;:&#34; 125&#34;}]) [constructorTemplate:FusionCharts:private] =&gt;&gt; [renderTemplate:FusionCharts:private] =&gt;)

使用手动方法(有效):

  

FusionCharts对象([constructorOptions:FusionCharts:private] =&gt;数组(&gt; [type] =&gt; column2d [id] =&gt; ex1 [宽度] =&gt; 600 [高度] =&gt; 400 [renderAt ] =&gt;&gt; chart-1 [dataFormat] =&gt; json [dataSource] =&gt; {&#34;图表&#34;:{&gt;&#34;标题&#34;:&#34; Harry&# 39; s SuperMart&#34;,&#34; subCaption&#34;:&#34;上个月排名前5位的商店&gt;收入&#34;,&#34; numberPrefix&#34;:&#34; $& #34;,&#34;主题&#34;:&#34;海洋&#34;},&#34;数据&#34;:[{&gt;&#34;标签&#34;:&#34;贝克斯菲尔德Central&#34;,&#34; value&#34;:&#34; 880000&#34;},{&#34; label&#34;:&#34; Garden Groove&gt; harbour&#34;,&#34 ;价值&#34;:&#34; 730000&#34;},{&#34;标签&#34;:&#34;洛杉矶Topanga&#34;,&gt;&#34;价值&#34;:&# 34; 590000&#34;},{&#34;标签&#34;:&#34; Compton-Rancho Dom&#34;,&#34;价值&#34;:&#34; 520000&#34;},{ &gt;&#34;标签&#34;:&#34; Daly City Serramonte&#34;,&#34; value&#34;:&#34; 330000&#34;}]})&gt; [constructorTemplate:FusionCharts: private] =&gt;&gt; [renderTemplate:FusionCha rts:private] =&gt; )

我看到了两个差异,手册在&#34;数据&#34;周围插入空格。和结束}参数。

2 个答案:

答案 0 :(得分:6)

有一种自动(并且更容易)的方式:

$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代表,label代表Name

详细了解json_encode

答案 1 :(得分:2)

作为总结,这是解决问题的部分,包括FirstOne的foreach声明:

$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);
    //print_r($jsonEncodedData);

    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 . '}');
        // Render the chart
        print_r($columnChart);
        $columnChart->render();
    ?>

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

       </body>

    </html>

感谢大家帮忙解决问题。