更改JSON输出的结构

时间:2019-07-26 22:08:39

标签: php json

如何调整函数以实现所需的JSON结构?

请注意,现在如何将每个对象的索引设置为土地合同的ID。那不是我想要的。我想更改的另一个是,对象以称为“ landcontracts”的数组形式呈现。

function read($pdo, $Id = null) {

    $params = [];
    $array = [];

    $sql = "SELECT lc.*, 
                   py.AnnualPriceYear AS `Year`,  
                   py.AnnualPriceAmount AS `Amount`
            FROM LandContract AS lc
            LEFT JOIN LandContractAnnualPrice AS py 
                ON py.LandContractId = lc.Id
            ";
    if ($Id) {
        $sql .= 'WHERE lc.Id = ?';
        $params[] = $Id;
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    while ($row = $stmt->fetch()) {
        // Fields we want to extract from the select statement into the array 
        $select_fields = ['Id', 'Name', 'LocationId', 'Link', 'Notes', 'LandOwnerId', 
                            'StartDate', 'EndDate', 'IsTerminated', 'PaymentInterval', 
                            'PriceType', 'FixedAnnualPrice '];

        if (!isset($array[$row['Id']])) {
            // initialize the subarray if it has not been set already 
            $array[$row['Id']] = array_intersect_key($row, array_flip($select_fields));

            if ($row['Year'] != null) {
                $array[$row['Id']]['AnnualPrices'] = [];
            } else {
                $array[$row['Id']]['AnnualPrice'] = $row['FixedAnnualPrice'];
            }
        }

        if ($row['Year'] != null) {
            $array[$row['Id']]['AnnualPrices'][] = ['Year' => $row['Year'], 'Amount' => $row['Amount']];
        }

    }

    if (empty($array)) {
        echo "No results";
        exit;
    }

    echo json_encode($array, JSON_UNESCAPED_UNICODE);

    $stmt = null;
}

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用正确的键将结果数组包装在另一个关联数组中,然后使用原始数组的config.json来重置键。

例如:

array_values