使用数据库关系/外键PHP构建JSON对象

时间:2016-05-26 19:01:07

标签: php json database orm foreign-key-relationship

我需要一些帮助。

基本上我需要做的是,它是数据库之间的简单映射关系(FK),并将其作为JSON(使用php)。

例如,我有两个抽象数据库:

1:客户

+-------+-----------+----------+
|  id   |    name   |  car_id  |
+-------+-----------+----------+

2:车

+-------+-----------+----------+
|  id   |    model  |  price   |
+-------+-----------+----------+

我需要一个JSON,如:

{
    "customers": [{
        "id": "1",
        "name": "First Customer",
        "car": {
            "id": "1",
            "model": "sampleCar",
            "price:": "19.33"
        }
    }, {
        "id": "2",
        "name": "second Customer",
        "car": {
            "id": "2",
            "model": "betterCar",
            "price:": "99.33"
        }
    }]
}

我正在使用MySQL来保存这些数据,但我可以更改数据库 - 我无法更改的唯一内容是PHP。

我的问题是: 有一种表演方式来做没有使用框架吗? (或者也许是一个只做它的框架?)

谢谢!

1 个答案:

答案 0 :(得分:1)

这是一个简单的JOIN查询,然后抓取循环会创建适当的数据。

$sql = "SELECT c.id AS cus_id, c.name, car.id AS car_id, car.model, car.price
        FROM customer AS c
        LEFT JOIN car ON car.id = c.car_id";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$customers = array();
while ($row = $stmt->fetch) {
    if ($row['car_id'] != null) {
        $car = array('id' => $row['car_id'],
                     'model' => $row['model'],
                     'price' => $row['price']);
    } else {
        $car = null;
    }
    $customers[] = array('id' => $row['cus_id'],
                         'name' => $row['name'],
                         'car' => $car);
}

$result = array('customers' => $customers);