2016-07-26 3 views
0

Я создаю API для приложения iOS и пытаюсь получить данные mySQL в строку JSON для обработки. Желаемый результат потребует подробных данных верхнего уровня, таких как имя и адрес клиента, а затем дополнительный массив заказанных продуктов.Вложенный вывод JSON в PHP

В обеих таблицах мне нужно много полей, и я надеюсь, что у них есть все поля. Я создал скрипт, чтобы сделать это, но результат сообщает об ошибках в валидаторе 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); 
} 

Выходной ток, как это:

enter image description here

Вот 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":"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... 

Я просто смущенный этим. Или мне нужно будет описать каждое поле в наборе данных для этого, чтобы вывести чистый JSON?

+0

Это может помочь увидеть оригинальный вывод в текстовом формате, а не то, что какой-то инструмент удалось интерпретировать из него в виде изображения. – Eiko

+0

Несомненно. Я добавлю. Это было просто для удобства чтения. – ABOO

ответ

1

Это не то, что ясно из вопроса, но я думаю, что нужно что-то вроде этого:

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

Если это так, вам нужно реорганизовать ваш код немного. Прежде всего, вы должны поместить массив products в массив $row_array, который должен быть $row, и не содержать его. Поскольку $row, кажется, объект с открытыми свойствами, вы не можете просто бросить $row в массив и присвоить его $row_array:

$row_array = (array) $row; 

Как вы можете видеть, нет необходимости для $row_array, который оборачивает $row, ваш $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 = (массив) $ row;» используемый ранее. Мне нравится! – ABOO

+0

Поскольку '$ row_array' действительно должен быть' $ row', но '$ row' - это объект, вы можете просто нарисовать его с помощью' (array) '. Я уточню ответ, чтобы сделать его более ясным. – deshack

Смежные вопросы