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

Posted

技术标签:

【中文标题】PHP PDO 将数组转换为不同的格式【英文标题】:PHP PDO Convert array to different format 【发布时间】:2016-04-01 22:53:13 【问题描述】:

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

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

使用融合图所需的以下格式

[

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

尝试了以下代码但没有结果,我的问题是我们不应该按照他们的要求以“”结尾:

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

我还想发布“手动”方法和“获取方法”之间的数组差异(在此编辑的上方)。

使用获取:

FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart- 1 [dataFormat] => json [dataSource] => "chart": >"caption":"Harry's SuperMart", "subCaption":"上个月按 >revenue 排名的前 5 家商店", "numberPrefix":"$ ", "主题":"海洋" , "数据": >["label":"John","value":"125","label":"Jerry","value":"125 ","label":"Jane","value":"125"] ) [constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )

使用手动方法(有效):

FusionCharts Object ( [constructorOptions:FusionCharts:private] => Array ( >[type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] => >chart- 1 [dataFormat] => json [dataSource] => "chart": >"caption":"Harry's SuperMart", "subCaption":"上个月按 >revenue 排名的前 5 家商店", "numberPrefix":"$ ", "主题":"海洋" , "数据": [ >"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" ] ) >[constructorTemplate:FusionCharts:private] => >[renderTemplate:FusionCharts:private] => )

我看到了两个不同之处,手册在“数据”和结尾的 参数周围插入了空格。

【问题讨论】:

那是JSON。使用json_encode() ? 最简单的选择任何你想要的(不要使用SELECT *)和json_encode 我们不应该以“”结尾。你试过吗? $jsonEncodedData . ''); 测试? 看起来成功了!谢谢FirstOne,我会发布一个答案来总结。感谢您耐心地帮助我。 没问题,我已将您的答案标记为答案并 +1,但您可以随意编辑。再次感谢 【参考方案1】:

有一种自动(而且更容易)的方法:

$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的信息。

【讨论】:

这可以通过查询SELECT Name AS label, Visits AS value FROM mysqltablejson_encode($results) 更有效地实现,因为数据库传输的负载更少并且没有额外的迭代。 @bansi 既然您在问题的评论中添加了此内容,我认为您想将其添加为答案。有些人不喜欢他们的评论“被盗”,所以我添加了我的作为替代。 如果你没问题,我可以在早上之前编辑并包含你的方法(现在真的很晚了)。这样,如果其他人愿意,他们就有时间添加它。 确保将其添加到答案中。它会让它变得更好 感谢您这么快发表评论。所以我尝试了替代方案 FirstOne。我实际上确实尝试过 json_encode,但我注意到输出无法正常工作或正在开发图表。然后我使用了你的 foreach 方法,仍然没有结果。为了确保它不是其他东西,我将原始数据放入其中进行测试。如果您使用站点数据,我将在下面发布有效的 php。任何帮助都会很棒。 @newpie,我看到你的更新了,你有没有试过代替"data": //$jsonEncodedData');,使用:"data": ' . $jsonEncodedData);(因为是单引号,请注意串联)【参考方案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>

感谢大家帮助解决问题。

【讨论】:

以上是关于PHP PDO 将数组转换为不同的格式的主要内容,如果未能解决你的问题,请参考以下文章

Magento:将 PDO 结果转换为 Varien 对象

JS数组到PHP并使用PDO更新MYSQL中的表

将 PHP 数组转换为对象的 JSON 数组

将 PHP 数组转换为 JSON 树

将对象对象转换为对象数组(PHP,Laravel)

如何使用 pdo 将字符串数组传递给 php 中的 plsql 例程