2016-07-26 11 views
0

iOSアプリケーション用のAPIを構築していて、処理のためにmySQLデータをJSON文字列に変換しようとしています。希望する出力には、顧客名と住所のような最上位の注文の詳細と注文された製品のサブアレイが必要です。PHPでネストされたJSON出力

両方のテーブルにかなりのフィールドがあり、必要なフィールドがすべてあることを願っています。これを行うためのスクリプトを作成しましたが、出力はJSONバリデータで不正な形式でレポートされています。ここで

は私のコードです:

$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); 
} 

電流出力は、このようなものです:私はちょうどよ

[{"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... 

enter image description here

ここでRAW出力が要求によって、ですこれで困った。または、クリーンなJSONを出力するために、データセットの各フィールドを列挙する必要がありますか?

+0

それは、テキスト形式で元の出力、いくつかのツールは、画像としてそれから解釈するように管理されていない何かを見るために役立つかもしれません。 – Eiko

+0

私はそれを追加します。それは純粋に読みやすさのためでした。 – ABOO

答えて

1

それは質問から明らかではないのですが、私はあなたがこのような何かが必要だと思う:これが正しければ、あなたのコードを少しリファクタリングする必要が

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

を。まず、配列$row_arrayの中に配列productsを入れなければなりません。配列は$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 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); 
+0

明確な説明をいただきありがとうございます。今はもっと意味をなさない。私は見たことがない "$ row_array =(配列)$行;"前に使用されました。好き! – ABOO

+0

'$ row_array'は実際には' $ row'であるべきですが、 '$ row'はオブジェクトであるため、'(array) 'でキャストできます。私はそれを明確にするために答えを更新します。 – deshack

関連する問題