使用Foreach制作一张桌子

时间:2014-05-19 09:37:12

标签: foreach json

我是PHP的新手,我这是为了向我的网站显示已在fdpp门户上传的内容

<?php $resp = file_get_contents("http://fdpp.blgs.gov.ph/api/documents?source=datatable&sSearch=kalinga"); 
$clean = json_decode($resp);

print_r($clean); ?>

这是结果:

stdClass Object
(
    [iTotalRecords] => 130035
    [iTotalDisplayRecords] => 879
    [sEcho] => 0
    [aaData] => Array
        (
            [0] => stdClass Object
                (
                    [lgu] => <a href=' http://fdpp.blgs.gov.ph/documents/view/129293'>CAR<br/>Kalinga<br />Balbalan</a>
                    [document] => <a href=' http://fdpp.blgs.gov.ph/documents/view/129293'>Local Disaster Risk Reduction and Management Fund Utilization (LDRRMF)</a>
                    [period] => Quarter 1 2014
                    [status] => Required &bull; SUBMITTED 
                    [desc] => The atng.
                )

            [1] => stdClass Object
                (
                    [lgu] => <a href=' http://fdpp.blgs.gov.ph/documents/view/129188'>CAR<br/>Kalinga<br />Balbalan</a>
                    [document] => <a href=' http://fdpp.blgs.gov.ph/documents/view/129188'>Manpower Complement</a>
                    [period] => Quarter 1 2014
                    [status] => Required &bull; SUBMITTED 
                    [desc] => The file ag.
                )

我应该将什么添加到我的代码中以将其放在列名为lgu,document,period的表中?我试过阅读foreach手册,但我无法弄明白有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

我必须同意PeeHaa(+1),但没有提供足够的信息,但我会尝试帮助你。

做出以下假设:

  1. 您有一个名为&#34; testdb&#34;
  2. 的本地MySQL数据库
  3. 您已安装PDO扩展程序
  4. 在&#34; testdb&#34;中,您有一个名为&#34; test_table&#34;的表。 4 列(id,lgu,document,period)
  5. 首先,您需要将json_decode中的第二个参数设置为true以返回关联数组而不是对象(PHP: json_decode)

    因此,基于有限的信息,这是一个工作版本:

    <?php
    $resp = file_get_contents("http://fdpp.blgs.gov.ph/api/documents?source=datatable&sSearch=kalinga");
    $clean = json_decode($resp,true);
    
    // Open connection to your MySQL DB
    $db = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
    
    // Parse the now-associative array and insert into table
    foreach($clean['aaData'] as $doc){
        $stmt = $db->prepare("INSERT INTO test_table(lgu,document,period) VALUES(:lgu,:document,:period)");
        $stmt->execute(array(':lgu' => $doc['lgu'], ':document' => $doc['document'], ':period' => $doc['period']));
    }
    ?>
    

    您应该提供更多信息以获得更准确的答案。

    但是,这应该让你朝着正确的方向前进。