简体   繁体   中英

Changing the structure of a JSON output

How can I adjust my function to achieve the desired JSON structure?

Notice how the index of each object is set to the land contract's Id right now. That's not how I want it. The other I'd like to change is that the objects are presented in an array called "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;
}

在此处输入图片说明

You can just wrap your array of results inside another associate array with the correct key, and take the array_values of the original array to reset the keys.

For example:

echo json_encode([
    'landcontacts' => array_values($array),
], JSON_UNESCAPED_UNICODE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM