How can I normalize/check a json object output it can run through a foreach loop (php)

Sunday, July 6, 2014

Maybe I just need to get some sleep, but I cannot figure this one out :( ... My problem is that the json output I have changes when it contains a single order vs multiple orders.


Here is an example json output of a single order:



{"Ack":"Success","OrderArray":{"Order":{"OrderID":"165921181012"}},"OrdersPerPage":"10","PageNumber":"1","ReturnedOrderCountActual":"1"}


Here is an example json output of multiple orders:



{"Ack":"Success","OrderArray":{"Order":[{"OrderID":"165921181012","OrderStatus":"Completed"},{"OrderID":"151330738592-1109250612005","OrderStatus":"Completed"},{"OrderID":"380931137567-501668037025","OrderStatus":"Completed"}]},"OrdersPerPage":"10","PageNumber":"1","ReturnedOrderCountActual":"3"}


The difference being the [ ]


Right now my code is as follows:



$json_o = json_decode($json);
foreach ($json_o->OrderArray->Order as $orderkey=>$o) { echo $o->OrderID; }


My first thought was to write an if statement to handle single orders, but when I try is_array neither of the outputs above are showing as arrays, and when I tried to use is_object both of the outputs above are showing as objects.


Is there another way I can check whether "Order" contains multiple objects? OR is there a way to add the [ ] around "OrderID" so that the foreach loop would run even if only one order exists?







http://ift.tt/1rCvyLB