Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/263.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用单个查询从相关数据库表中回显嵌套JSON数组?_Php_Json_Multidimensional Array_Pdo_Relational Database - Fatal编程技术网

Php 使用单个查询从相关数据库表中回显嵌套JSON数组?

Php 使用单个查询从相关数据库表中回显嵌套JSON数组?,php,json,multidimensional-array,pdo,relational-database,Php,Json,Multidimensional Array,Pdo,Relational Database,我有两个数据库表,其中包含有关土地合同的信息。它们与land\u contract\u year\u price.land\u contract\u id->land\u contract.land\u id相关 表“土地合同” 表“土地合同年价格” 如果土地合同在现场土地合同价格类型中具有“Rörligt pris”值,则表中有相关值 土地合同\年价格。目前我正在做两个查询,每个表一个。然后,我合并结果并将土地合同呈现为一个嵌套的JSON数组,如下所示: 第1版 [ { "l

我有两个数据库表,其中包含有关土地合同的信息。它们与
land\u contract\u year\u price.land\u contract\u id
->
land\u contract.land\u id
相关

表“土地合同”

表“土地合同年价格”

如果土地合同在现场土地合同价格类型中具有“Rörligt pris”值,则表中有相关值
土地合同\年价格
。目前我正在做两个查询,每个表一个。然后,我合并结果并将土地合同呈现为一个嵌套的JSON数组,如下所示:

第1版

[  
 {  
  "land_contract_id":118,
  "land_contract_name":"Avtalsnamn",
  "location_id":71,
  "land_contract_link":"",
  "land_contract_notes":"",
  "land_owner_id":2,
  "land_contract_start_date":"2019-07-25",
  "land_contract_end_date":"2023-07-25",
  "land_contract_terminated":"false",
  "land_contract_payment_interval":"Halv\u00e5rsvis",
  "land_contract_price_type":"R\u00f6rligt \u00e5rspris",
  "land_contract_fixed_annual_price":null,
  "land_contract_annual_prices":[  
    {"year":1, "price":873.00},
    {"year":2, "price":77289.00},
    {"year":3, "price":8.00},
    {"year":4, "price":0.00},
    {"year":5, "price":8729.00}
  ]
 }
]
如果土地合同在“土地合同价格类型”字段中的值为“Fast pris”,则表中没有相关值
土地合同\年价格
。在这种情况下,我会像这样展示土地合同(末尾没有额外的数组):

第2版

[
 {
  "land_contract_id":13,
  "land_contract_name":null,
  "location_id":null,
  "land_contract_link":"https:\/\/www.something.com\/preview\/Sl%C3%A4pvdam%20Edda\/Kddal\/Bddkta\/Besika%20Markavtal%20%20Halmstad%202016-03-08.pdf?role=personal",
  "land_contract_notes":"",
  "land_owner_id":null,
  "land_contract_start_date":"2016-03-08",
  "land_contract_end_date":"2026-03-08",
  "land_contract_terminated":"true",
  "land_contract_payment_interval":"\u00c5rsvis",
  "land_contract_price_type":"Fast \u00e5rspris",
  "land_contract_fixed_annual_price":"6000.00"
 }
]
我没有想到的是,当我拿到所有的土地合同时,这个解决方案是不好的。如果我要对另一个表进行第二次查询,只要土地合同的字段land_contract_price_type中的值为“Rörligt pris”,我就要进行数百次额外的查询

当土地合同的字段land_contract_price_type中的值为“Rörligt pris”时,是否有方法通过一(1)个查询创建嵌套的JSON数组

谢谢

下面是我当前的代码

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

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

    $sql = "SELECT  lc.Id, lc.Name, lc.LocationId, l.Name AS LocationName, lc.Notes, lc.LandOwnerId, lo.Name AS LandOwnerName, lc.StartDate, lc.EndDate, lc.IsTerminated, lc.PaymentInterval, lc.PriceType, lc.FixedAnnualPrice, lc.Link, lc.Created, lc.Updated, lcap.AnnualPriceYear AS Year, lcap.AnnualPriceAmount AS Amount
            FROM LandContract lc
            LEFT JOIN Location l ON l.Id = lc.LocationId
            LEFT JOIN LandOwner lo ON lo.Id = lc.LandOwnerId
            LEFT JOIN LandContractAnnualPrice lcap ON lcap.LandContractId = lc.Id  
            ORDER BY lc.Id  DESC, lcap.AnnualPriceYear DESC
            ";
    if ($Id) {
        $sql .= 'WHERE lc.Id = ?';
        $params[] = $Id;
    }

    echo $sql;

    $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', 'LocationName', 'Link', 'Notes', 'LandOwnerId', 'LandOwnerName',
                            'StartDate', 'EndDate', 'IsTerminated', 'PaymentInterval', 
                            'PriceType', 'FixedAnnualPrice ', 'Created', 'Updated'];

        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)) {
        $ResponseMessage = new ResponseMessage();
        $ResponseMessage->Status = 'Error';
        $ResponseMessage->Message = 'No results';
        echo json_encode($ResponseMessage, JSON_UNESCAPED_UNICODE);
        exit;
    }

    $Response = array();

    if ($ResponseMessage) {
        $Response['Status'] = $ResponseMessage->Status;
        $Response['Message'] = $ResponseMessage->Message;
    }

    $Response['LandContracts'] = array_values($array);

    echo json_encode($Response, JSON_UNESCAPED_UNICODE);

    $stmt = null;
}

最好使用
JOIN
查询,然后根据结果构造数组-在循环中使用查询通常是一个非常糟糕的主意,并且可以使用
JOIN
作为指示符

您希望使用
左联接
,在两个表中的
土地契约id
上联接它们

然后循环您的结果,并构建您的数组,一旦完成,就可以将其编码为JSON字符串

$params=[];
$array=[];
$sql=“选择lc.*,
py.土地\合同\年\价格\年为“年”,
py.土地\合同\年\价格\金额为`金额`
从土地承包合同中提取信用证
左联土地\合同\年\价格为py
在py.land\u contract\u id=lc.land\u contract\u id上
";
如果(isset($\u POST['land\u contract\u id')){
$sql.='其中lc.land_contract_id=?';
$params[]=$\u POST[“土地合同id”];
}
$stmt=$pdo->prepare($sql);
$stmt->execute($params);
而($row=$stmt->fetch()){
//要从select语句提取到数组中的字段
$select_fields=['land_contract_id','land_contract_name','location_id','land_contract_link','land_contract_notes','land_owner_id',
‘土地合同开始日期’、‘土地合同结束日期’、‘土地合同终止’、‘土地合同付款间隔’,
“土地合同价格类型”、“土地合同固定价格年度价格”];
如果(!isset($array[$row['land\u contract\u id']])){
//如果尚未设置子阵列,则初始化该子阵列
$array[$row['land\u contract\u id']=array\u intersect\u key($row,array\u flip($select\u fields));
如果($row['year']!=null){
$array[$row['land\u contract\u id']['land\u contract\u year\u prices']=[];
}否则{
$array[$row['land_contract_id']['land_contract_year_price']=$row['land_contract_fixed_year_price'];
}
}
如果($row['year']!=null){
$array[$row['land_contract_id']['land_contract_year_prices']['year'=>$row['year'],'amount'=>$row['amount'];
}
}
if(空($array)){
回应“没有结果”;
出口
}
echo json_encode($array,json_UNESCAPED_UNICODE);

您最好使用
连接查询,然后根据结果构造数组-在循环中进行查询通常是一个非常糟糕的主意,这是一个可以使用
连接的指示器

您希望使用
左联接
,在两个表中的
土地契约id
上联接它们

然后循环您的结果,并构建您的数组,一旦完成,就可以将其编码为JSON字符串

$params=[];
$array=[];
$sql=“选择lc.*,
py.土地\合同\年\价格\年为“年”,
py.土地\合同\年\价格\金额为`金额`
从土地承包合同中提取信用证
左联土地\合同\年\价格为py
在py.land\u contract\u id=lc.land\u contract\u id上
";
如果(isset($\u POST['land\u contract\u id')){
$sql.='其中lc.land_contract_id=?';
$params[]=$\u POST[“土地合同id”];
}
$stmt=$pdo->prepare($sql);
$stmt->execute($params);
而($row=$stmt->fetch()){
//要从select语句提取到数组中的字段
$select_fields=['land_contract_id','land_contract_name','location_id','land_contract_link','land_contract_notes','land_owner_id',
‘土地合同开始日期’、‘土地合同结束日期’、‘土地合同终止’、‘土地合同付款间隔’,
“土地合同价格类型”、“土地合同固定价格年度价格”];
如果(!isset($array[$row['land\u contract\u id']])){
//如果尚未设置子阵列,则初始化该子阵列
$array[$row['land\u contract\u id']=array\u intersect\u key($row,array\u flip($select\u fields));
如果($row['year']!=null){
$array[$row['land\u contract\u id']['land\u contract\u year\u prices']=[];
}否则{
$array[$row['land_contract_id']['land_contract_year_price']=$row['land_contract_fixed_year_price'];
}
}
如果($row['year']!=null){
$array[$row['land_contract_id']['land_contract_year_prices']['year'=>$row['year'],'amount'=>$row['amount'];
}
}
if(空($array)){
回应“没有结果”;
出口
}
echo json_encode($array,json_UNESCAPED_UNICODE);
It