Php 更改JSON输出的结构

Php 更改JSON输出的结构,php,json,Php,Json,如何调整函数以实现所需的JSON结构 请注意,现在如何将每个对象的索引设置为土地合同的Id。这不是我想要的。另一个我想更改的是,对象以一个名为“landcontracts”的数组显示 您可以使用正确的键将结果数组包装到另一个关联数组中,然后使用原始数组的数组\u值来重置键 例如: echo json\u编码([ “landcontacts”=>array\u值($array), ],JSON_UNESCAPED_UNICODE); $array=['landcontracts'=>array\u

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

请注意,现在如何将每个对象的索引设置为土地合同的Id。这不是我想要的。另一个我想更改的是,对象以一个名为“landcontracts”的数组显示


您可以使用正确的键将结果数组包装到另一个关联数组中,然后使用原始数组的
数组\u值来重置键

例如:

echo json\u编码([
“landcontacts”=>array\u值($array),
],JSON_UNESCAPED_UNICODE);

$array=['landcontracts'=>array\u值($array)]
?很难说。或者,你可以在处理数据时构造你的数组。哇,这真是太棒了。非常感谢你!
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;
}