当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《PHPPDO将数组转换为不同的格式》经验,为你挑选了1个好方法。

我试图使用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时,我无法让它工作.思考?


   
    FusionCharts XT - Column 2D Chart - Data from a database
    

    

    
  

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

    

==============编辑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();
?>

    

我想在"手动"方法和"获取方法"(在此编辑中的上方)之间发布数组差异.

用fetch:

FusionCharts对象([constructorOptions:FusionCharts:private] => Array(> [type] => column2d [id] => ex1 [width] => 600 [height] => 400 [renderAt] = >> chart-1 [dataFormat ] => json [dataSource] => {"chart":{>"caption":"Harry's SuperMart","subCaption":"上个月按收入排名前5位的商店","numberPrefix":"$","主题":"ocean"},"data":> [{"label":"John","value":"125"},{"label":"Jerry","value":"125"}, {"label":"Jane","value":"125"}])[constructorTemplate:FusionCharts:private] = >> [renderTemplate:FusionCharts:private] =>)

使用手动方法(有效):

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

我手边看到两个不同之处,手册在"数据"和结尾}参数周围插入空格.



1> FirstOne..:

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

$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"},...]

注:我认为value是代表Visitlabel通过Name.

阅读更多关于json_encode的信息.


这可以通过查询`SELECT Name AS label,Visits AS value FROM mysqltable`和`json_encode($ results)`来实现,因为数据库传输的负载较少而且没有额外的迭代.
推荐阅读
Chloemw
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有