0

I have a call to a webservice which is returning json data. I use:

$response_json = json_decode ( $response );

If I print_r($response) I get this:

stdClass Object
(
    [meta] => stdClass Object
    (
        [no_of_pages] => 3
        [current_page] => 1
        [max_items_per_page] => 250
        [no_of_items] => 740
    )

[data] => Array
    (
        [0] => stdClass Object
            (
                [orderid] => 322191645
                [customer] => stdClass Object
                    (
                        [city] => FELIXSTOWE

I am trying to loop through the orders:

foreach($response_json as $orders) {
    echo $orders.['data'].[0].['orderid'];
    }

but I keep getting:

Catchable fatal error: Object of class stdClass could not be converted to string. I have also tried many other ways, but I just can't seem to access the data in a loop. Thanks in advance.

Paul
  • 431
  • 2
  • 10
  • 24

2 Answers2

4

You can json_decode as associative array.

$response = json_decode ($response, true);

foreach($response as $orders) {
    echo $orders[0]['orderid'];
}
KiwiJuicer
  • 1,952
  • 14
  • 28
  • OK if I do: $response_json = json_decode ( $response , true); foreach($response_json as $orders) { echo $orders.['data'].[0].['orderid']; – Paul Dec 09 '15 at 09:37
  • echo $orders['data'][0]['orderid']; I get no output with this?? – Paul Dec 09 '15 at 09:41
  • Sorry, I corrected my answer. Its without ['data'] as you loop already through the array. To be sure do "print_r($orders);" – KiwiJuicer Dec 09 '15 at 09:42
  • Sorry don't know what I am doing wrong here... foreach($response_json as $orders) { foreach($orders as $order) { echo $order['orderid']; }} Only outputs 2 orders with Warning: Invalid argument supplied for foreach() in – Paul Dec 09 '15 at 10:10
  • 1
    Loop through ***$response_json['data']*** – KiwiJuicer Dec 09 '15 at 10:12
1
  1. Don't use dots between brackets.
  2. Skip "data" in your array.

Example:

foreach($response_json as $orders) {
    echo $orders[0]['orderid'];
}
Kamil P
  • 782
  • 1
  • 12
  • 29