PHP 中的嵌套 JSON 输出 [英] Nested JSON output in PHP

查看:46
本文介绍了PHP 中的嵌套 JSON 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 iOS 应用程序构建 API,并尝试将 mySQL 数据转换为 JSON 字符串进行处理.所需的输出需要顶级订单详细信息,例如客户姓名和地址,然后是订购的产品子数组.

我需要的两个表中有很多字段,我希望拥有所有字段.我已经构建了一个脚本来执行此操作,但输出在 JSON 验证器中报告为格式错误.

这是我的代码:

$orders = $db->get_results("SELECT ords.serial as ID, cust.title, cust.name, cust.surname, cust.address, cust.address2, cust.town, cust.县、cust.postcode、cust.phone、cust.height、cust.weight、cust.houseType、cust.parking、cust.access、ords.furnitureRem、ords.furnitureRemDetails、ords.comments FROM 订单作为 ords 加入客户作为 cust ONords.customerid = cust.serial JOIN order_detail as odeet ON ords.serial = odeet.orderid JOIN `user` as us ON us.id = ords.user_id WHERE us.id='".$_REQUEST['userID']."' GROUP BY ords.serial ORDER BY cust.serial DESC");$json_response = array();//创建一个数组foreach ( $orders as $row ){$row_array = array();$row_array[] = $row;$ord_id = $row->ID;$orders2 = $db->get_results("SELECT * FROM order_detail as ordJOIN 产品作为 prod ON ord.productid = prod.idWHERE ord.orderid = ".$ord_id);foreach ( $orders2 作为 $vorder2 ) {{$row_array['products'][] = $vorder2;}array_push($json_response, $row_array);//推送数组中的值}回声 json_encode($json_response);}

当前输出是这样的:

这是 RAW 输出,应要求提供:

[{"0":{"ID":"756","title":"Mr","name":"John","surname":"Smith","address":"Address Line 1","address2":"Address Line 2","town":"Town","county":"County","postcode":"PO57 8DE","phone":"0777777777777","height":"6ft","weight":"14st","houseType":"Flat","parking":"none","access":"没问题","furnitureRem":"0","furnitureRemDetails":null,"comments":null},"products":[{"orderid":"756","productid":"2","price":"6500","status":"1","id":"2","type":"Chair","style":"Surrey","action":"Single Motor 2 Way Tilt in Space","weightCap":"35st","height":"14\"","width":"24\"","internalWidth":null,"length":null,"internalLength":null,"depth":"16\"","fabric":"Leather","fabricCode":"LR43","backStyle":"Waterfall","cushionFabric":"Leather","cushionFabricCode":"LR43","backHeight":"32\"","armHeight":"7\"","seatingOptions":"Memory Foam","armOption":"Scrolled","backupBattery":"2x Backup","headRoll":"1","headCover":"1","seatCover":"0","armCover":"0","armCap":"1","pocket":"左","loop":"左","antimacassar":"0","freedom":"1","heatMassage":"0","castorsGlides":"Castors","footPlate":"0","seatDepthAdj":"0","doorFrame":null,"additionalCover":"0","scViscoform":"0","scPommelViscoform":"0","scLiquiform":"0","scPommelLiquiform":"0","scCelliform":"0","scAirform":"0","scDynaform":"0","bsWaterfall":"0","bsComfortLateral":"0","bsProfileWaterfall":"0","bsProfileComfortLateral":"0","bsSupportLateral":"0","bsProfileSupportLateral":"0","hsLargeProfileHeadrest":"0","hsSmallHeadPillow":"0","hsSmallProfileHeadPillow":"0","hsMidlineHeadrest":"0","woodColour":"0","frameColour":null,"baseColour":null,"headFootBoard":null,"mattressType":null,"productHeightLowest":null,"productHeightHighest":null,"liftingPoles":null,"grabRails":null,"readingLight":"0","existingBedHeight":null,"legHeight":null,"drawerOptions":null,"hoistCutouts":"0","cotSides":null,"liftingPole":"0","sideRetention":"0","linked":"0","rrp":null,"stock":"0"}]}][{"0":{"ID":"756","title":"Mr","name":"John","surname":"Smith","address":"地址行 1","address2":"Address Line 2","town":"Town","county":"County","postcode":"PO57 8DE","phone":"0777777777777","height":"6ft","weight":"14st","houseType":"Flat","parking":"none","access":"没问题","furnitureRem":"0","furnitureRemDetails":null,"comments":null},"products":[{"orderid":"756","productid":"2","price":"6500","status":"1","id":"2","type":"Chair","style":"Surrey","action":"Single Motor 2 Way Tilt in Space","weightCap":"35st","height":"14\"","width":"24\"","internalWidth":null,"length":null,"internalLength":null,"depth":"16\"","fabric":"Leather","fabricCode":"LR43","backStyle":"Waterfall","cushionFabric":"Leather","cushionFabricCode":"LR43","backHeight":"32\"","armHeight":"7\"","seatingOptions":"Memory Foam","armOption":"Scrolled","backupBattery":"2x Backup","headRoll":"1","headCover":"1","seatCover":"0","armCover":"0","armCap":"1","pocket":"左","loop":"左","antimacassar":"0","freedom":"1","heatMassage":"0","castorsGlides":"Castors","footPlate":"0","seatDepthAdj":"0","doorFrame":null,"additionalCover":"0","scViscoform":"0","scPommelViscoform":"0","scLiquiform":"0","scPommelLiquiform":"0","scCelliform":"0","scAirform":"0","scDynaform":"0","bsWaterfall":"0","bsComfortLateral":"0","bsProfileWaterfall":"0","bsProfileComfortLateral":"0","bsSupportLateral":"0","bsProfileSupportLateral":"0","hsLargeProfileHeadrest":"0","hsSmallHeadPillow":"0","hsSmallProfileHeadPillow":"0","hsMidlineHeadrest":"0","woodColour":"0","frameColour":null,"baseColour":null,"headFootBoard":null,"mattressType":null,"productHeightLowest":null,"productHeightHighest":null,"liftingPoles":null,"grabRails":null,"readingLight":"0","existingBedHeight":null,"legHeight":null,"drawerOptions":null,"hoistCutouts":"0","cotSides":null,"liftingPole":"0","sideRetention":"0","linked":"0","rrp":null,"stock":"0"}]},{"0":{"ID":"756",""title":"先生","name":"John","sur...

我只是被这个难住了.还是我需要逐项列出数据集中的每个字段才能输出干净的 JSON?

解决方案

问题不是很清楚,但我认为你需要这样的东西:

<预><代码>[{身份证":123,...产品": [{"foo": "酒吧"},{"foo": "baz"}]},{...}]

如果这是正确的,您需要稍微重构一下您的代码.首先,你要把products数组放在$row_array数组里面,应该是$row,而不是包含它.由于 $row 似乎是一个具有公共属性的对象,您可以将 $row 强制转换为数组并将其分配给 $row_array:

$row_array = (array) $row;

如您所见,不需要包含 $row$row_array,您的 $row_array 应该是您的 $row.

最后,当您只需要在数组末尾推送一个元素时,请避免使用 array_push():

$json_response[] = $row_array;

array_push()快.

您需要的最后一段代码如下:

$orders = $db->get_results(("SELECT ords.serial as ID, cust.title, cust.name, cust.surname, cust.address, cust.address2, cust.town, cust.county, cust.postcode, cust.phone, cust.height, cust.weight, cust.houseType, cust.parking, cust.access, ords.furnitureRem, ords.furnitureRemDetails, ords.comments FROM orders as ords 加入客户作为 custON ords.customerid = cust.serial JOIN order_detail as odeet ON ords.serial = odeet.orderid JOIN `user` as us ON us.id = ords.user_id WHERE us.id='".$_REQUEST['userID']."' GROUP BY ords.serial ORDER BY cust.serial DESC");$json_response = array();foreach ( $orders as $row ) {$row_array = (array) $row;$ord_id = $row->ID;$orders2 = $db->get_results("SELECT * FROM order_detail as ordJOIN 产品作为 prod ON ord.productid = prod.idWHERE ord.orderid = ".$ord_id);foreach ( $orders2 作为 $vorder2 ) {$row_array['products'][] = $vorder2;}$json_response[] = $row_array;}回声 json_encode($json_response);

I'm building an API for an iOS app and trying to get the mySQL data into a JSON string for processing. The desired output would require top level order details like customer name and address and then a sub array of products ordered.

There are quite a few fields in both tables i need and it i'm hoping to have all fields. I've built a script to do this, but the output is reporting as malformed in a JSON validator.

Here's my code:

$orders = $db->get_results("SELECT ords.serial as ID, cust.title, cust.name, cust.surname, cust.address, cust.address2, cust.town, cust.county, cust.postcode, cust.phone, cust.height, cust.weight, cust.houseType, cust.parking, cust.access, ords.furnitureRem, ords.furnitureRemDetails, ords.comments FROM orders as ords JOIN customers as cust ON ords.customerid = cust.serial JOIN order_detail as odeet ON ords.serial = odeet.orderid JOIN `user` as us ON us.id = ords.user_id  WHERE us.id='".$_REQUEST['userID']."' GROUP BY ords.serial ORDER BY cust.serial DESC"); 

$json_response = array(); //Create an array
foreach ( $orders as $row )
{
    $row_array = array();
    $row_array[] = $row;        
    $ord_id = $row->ID;  

    $orders2 = $db->get_results("SELECT * FROM order_detail as ord
    JOIN products as prod ON ord.productid = prod.id
    WHERE ord.orderid = ".$ord_id);
    foreach ( $orders2 as $vorder2 ) {
    {
        $row_array['products'][] = $vorder2;
    }
    array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response);
}

The current output is like this:

Here's the RAW output, by request:

[{"0":{"ID":"756","title":"Mr","name":"John","surname":"Smith","address":"Address Line 1","address2":"Address Line 2","town":"Town","county":"County","postcode":"PO57 8DE","phone":"0777777777777","height":"6ft","weight":"14st","houseType":"Flat","parking":"none","access":"No problems","furnitureRem":"0","furnitureRemDetails":null,"comments":null},"products":[{"orderid":"756","productid":"2","price":"6500","status":"1","id":"2","type":"Chair","style":"Surrey","action":"Single Motor 2 Way Tilt in Space","weightCap":"35st","height":"14\"","width":"24\"","internalWidth":null,"length":null,"internalLength":null,"depth":"16\"","fabric":"Leather","fabricCode":"LR43","backStyle":"Waterfall","cushionFabric":"Leather","cushionFabricCode":"LR43","backHeight":"32\"","armHeight":"7\"","seatingOptions":"Memory Foam","armOption":"Scrolled","backupBattery":"2x Backup","headRoll":"1","headCover":"1","seatCover":"0","armCover":"0","armCap":"1","pocket":"Left","loop":"Left","antimacassar":"0","freedom":"1","heatMassage":"0","castorsGlides":"Castors","footPlate":"0","seatDepthAdj":"0","doorFrame":null,"additionalCover":"0","scViscoform":"0","scPommelViscoform":"0","scLiquiform":"0","scPommelLiquiform":"0","scCelliform":"0","scAirform":"0","scDynaform":"0","bsWaterfall":"0","bsComfortLateral":"0","bsProfileWaterfall":"0","bsProfileComfortLateral":"0","bsSupportLateral":"0","bsProfileSupportLateral":"0","hsLargeProfileHeadrest":"0","hsSmallHeadPillow":"0","hsSmallProfileHeadPillow":"0","hsMidlineHeadrest":"0","woodColour":"0","frameColour":null,"baseColour":null,"headFootBoard":null,"mattressType":null,"productHeightLowest":null,"productHeightHighest":null,"liftingPoles":null,"grabRails":null,"readingLight":"0","existingBedHeight":null,"legHeight":null,"drawerOptions":null,"hoistCutouts":"0","cotSides":null,"liftingPole":"0","sideRetention":"0","linked":"0","rrp":null,"stock":"0"}]}][{"0":{"ID":"756","title":"Mr","name":"John","surname":"Smith","address":"Address Line 1","address2":"Address Line 2","town":"Town","county":"County","postcode":"PO57 8DE","phone":"0777777777777","height":"6ft","weight":"14st","houseType":"Flat","parking":"none","access":"No problems","furnitureRem":"0","furnitureRemDetails":null,"comments":null},"products":[{"orderid":"756","productid":"2","price":"6500","status":"1","id":"2","type":"Chair","style":"Surrey","action":"Single Motor 2 Way Tilt in Space","weightCap":"35st","height":"14\"","width":"24\"","internalWidth":null,"length":null,"internalLength":null,"depth":"16\"","fabric":"Leather","fabricCode":"LR43","backStyle":"Waterfall","cushionFabric":"Leather","cushionFabricCode":"LR43","backHeight":"32\"","armHeight":"7\"","seatingOptions":"Memory Foam","armOption":"Scrolled","backupBattery":"2x Backup","headRoll":"1","headCover":"1","seatCover":"0","armCover":"0","armCap":"1","pocket":"Left","loop":"Left","antimacassar":"0","freedom":"1","heatMassage":"0","castorsGlides":"Castors","footPlate":"0","seatDepthAdj":"0","doorFrame":null,"additionalCover":"0","scViscoform":"0","scPommelViscoform":"0","scLiquiform":"0","scPommelLiquiform":"0","scCelliform":"0","scAirform":"0","scDynaform":"0","bsWaterfall":"0","bsComfortLateral":"0","bsProfileWaterfall":"0","bsProfileComfortLateral":"0","bsSupportLateral":"0","bsProfileSupportLateral":"0","hsLargeProfileHeadrest":"0","hsSmallHeadPillow":"0","hsSmallProfileHeadPillow":"0","hsMidlineHeadrest":"0","woodColour":"0","frameColour":null,"baseColour":null,"headFootBoard":null,"mattressType":null,"productHeightLowest":null,"productHeightHighest":null,"liftingPoles":null,"grabRails":null,"readingLight":"0","existingBedHeight":null,"legHeight":null,"drawerOptions":null,"hoistCutouts":"0","cotSides":null,"liftingPole":"0","sideRetention":"0","linked":"0","rrp":null,"stock":"0"}]},{"0":{"ID":"756",""title":"Mr","name":"John","sur...

I'm just stumped with this one. Or am I going to need to itemise each field in the dataset for this to output a clean JSON?

解决方案

It's not that clear from the question, but I think you need something like this:

[
  {
    "ID": 123,
    ...
    "products": [
      {
        "foo": "bar"
      },
      {
        "foo": "baz"
      }
    ]
  },
  {
    ...
  }
]

If this is right, you need to refactor your code a little bit. First of all, you have to put the products array inside the $row_array array, which should be $row, not contain it. Since $row seems to be an object with public properties, you can just cast $row to array and assign it to $row_array:

$row_array = (array) $row;

As you can see, no need for a $row_array that wraps the $row, your $row_array should be your $row.

In the end, avoid using array_push() when you have to push only one element at the end of the array:

$json_response[] = $row_array;

Is faster than array_push().

The final piece of code you need is just this:

$orders = $db->get_results(("SELECT ords.serial as ID, cust.title, cust.name, cust.surname, cust.address, cust.address2, cust.town, cust.county, cust.postcode, cust.phone, cust.height, cust.weight, cust.houseType, cust.parking, cust.access, ords.furnitureRem, ords.furnitureRemDetails, ords.comments FROM orders as ords JOIN customers as cust ON ords.customerid = cust.serial JOIN order_detail as odeet ON ords.serial = odeet.orderid JOIN `user` as us ON us.id = ords.user_id  WHERE us.id='".$_REQUEST['userID']."' GROUP BY ords.serial ORDER BY cust.serial DESC");

$json_response = array();
foreach ( $orders as $row ) {
    $row_array = (array) $row;
    $ord_id = $row->ID;

    $orders2 = $db->get_results("SELECT * FROM order_detail as ord
        JOIN products as prod ON ord.productid = prod.id
        WHERE ord.orderid = ".$ord_id);
    foreach ( $orders2 as $vorder2 ) {
        $row_array['products'][] = $vorder2;
    }
    $json_response[] = $row_array;
}
echo json_encode($json_response);

这篇关于PHP 中的嵌套 JSON 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆