【问题标题】:Json encode for nested data using PDO PHP使用 PDO PHP 对嵌套数据进行 Json 编码
【发布时间】:2012-08-14 04:04:59
【问题描述】:

我有以下表格:

+---------+-----------+      +----------+---------+-------------+
| item_id | item_name |      | image_id | item_id |  image_url  |
+---------+-----------+      +----------+---------+-------------+
|       1 | phone     |      |        1 |       1 | http://url1 |
|       2 | computer  |      |        2 |       1 | http://url2 |
|       3 | keyboard  |      |        3 |       2 | http://url2 |
+---------+-----------+      +----------+---------+-------------+

我应该在 php 中使用 PDO 和 json 编码做什么来获得以下输出:

[
    {
        "item_id":"1",
        "name":"phone",
        "images": [
            {
                "image_id":"1",
                "url":"http://url1"
            },
            {
                "image_id":"2",
                "url":"http://url2"
            }
        ]
    },
    {
        "item_id":"2",
        "name":"computer",
        "images": [
            {
                "image_id":"3",
                "url":"http://url3"
            }
        ]
    },
    {
        "item_id":"3",
        "name":"keyboard",
        "images": []
    }
]

我是否必须在 foreach 循环中使用 foreach 才能获得此结果?

【问题讨论】:

  • 我只看到需要一个 foreach 循环。使用item_iditem_name 获取结果。然后你遍历那些。每个item_id 执行一个查询并将结果存根到父数组中。
  • 我需要跟踪我当前正在处理的项目的外部循环。

标签: php json pdo


【解决方案1】:

不,使用单个循环和单个 SQL 查询。

首先是 SQL 查询

SELECT im.image_id, im.image_url, im.item_id
       it.item_name
FROM images im 
   LEFT JOIN items it ON it.item_id=im.item_id
ORDER BY im.item_id, im.image_id

而您的 PHP(意译)是:

$lastItemId = -1;
$aJson = array();
while ($row = GetNextRow()) {    // Depends on your class
    $itemID = $row['item_id'];
    if (!isset($aJson[$itemID])) {
        $aJson[$itemID] = array('item_id'=$itemID, 'item_name'=$row['item_name'], images=>array());
    }
    $aJson[$itemID]['images'] = array('image_id'=>$row['image_id'], 'image_url'=>$row['image_url']);

}
echo json_encode($aJson);

你应该可以从那里调整?

【讨论】:

  • 谢谢罗比!晚上我会尝试这样做
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-24
  • 1970-01-01
  • 2019-05-05
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多