【问题标题】:using Foreach to make a table使用 Foreach 制作表格
【发布时间】:2014-05-19 09:37:11
【问题描述】:

我是 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、文档、句点的表中?我尝试阅读 foreach 手册,但我不知道有人可以帮助我吗?

【问题讨论】:

  • 如果没有您的尝试并告诉我们您遇到的问题,几乎不可能帮助您。
  • 澄清一下,他似乎正在尝试将 jQuery DataTables 库与服务器端处理一起使用。 Here's an example.

标签: foreach json


【解决方案1】:

我必须同意 PeeHaa (+1) 的观点,但我会尽力帮助您。

做了以下假设:

  1. 您有一个名为“testdb”的本地 MySQL 数据库
  2. 您已安装 PDO 扩展
  3. 在“testdb”中,您有一个名为“test_table”的表,其中包含 4 列(id、lgu、文档、句点)

首先,您需要将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']));
}
?>

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

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

【讨论】:

    猜你喜欢
    • 2018-12-16
    • 2013-10-01
    • 2018-01-01
    • 1970-01-01
    • 2013-09-27
    • 2022-12-09
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多