PHP Object Array from API call

I have made an API call $client->orders->get() and I get a response with the data formatted like:

Array ( [0] => stdClass Object ( [id] => 5180 [order_number] => 5180 [created_at] => 2016-12-21T14:50:08Z [updated_at] => 2016-12-21T15:01:51Z [completed_at] => 2016-12-21T15:01:52Z [status] => completed [currency] => GBP [total] => 29.00 [subtotal] => 29.00 [total_line_items_quantity] => 1 [total_tax] => 0.00 [total_shipping] => 0.00 [cart_tax] => 0.00 [shipping_tax] => 0.00 [total_discount]...........

So I loop through the data:

foreach ( $client->orders->get() as $order ) {

// skip guest orders (e.g. orders with customer ID = 0)
print_r($order);
    echo $order[0];
    echo $order->subtotal;
}

Trouble I have is outputting the data, if I use the print_r function I get an output but I don't know how to access the individual elements of the array.

If I try:

echo $order[0].[id];

I get:

Catchable fatal error: Object of class stdClass could not be converted to string in.

I have searched high and low on this but I just can't find anything I understand. Help please... :)


The $order within the following loop

foreach ( $client->orders->get() as $order ) { .. }

is each of elements that belongs to this $client->orders->get() array and they are in the form of object.

thus to output ( for eg the subtotal entry) you do echo $order->subtotal :

foreach ( $client->orders->get() as $order ) { $order->subtotal }
  • echo $order[0] (inside the loop) is invalid, because doing so is treating the $order as an array meanwhile its type is object. Do $order->somefields instead to reference its properties.
  • print_r($order) (inside the loop) is valid because you can use print_r to print the properties of object.
  • $client->orders->get()[0]->subtotal (if put outside the loop) is also valid.
  • Just in case the array's elements contains both form of object or array

    $myarray = $client->orders->get();
    
  • // True because the first element is object echo (is_object($myarray[0])) ? 'True':'False';

  • // False because the first element is object, not an array echo is_array($myarray[0]) ? 'True':'False';

  • And for this

    // the same with echo is_array($client->orders->get()) ? 'True':'False';
    echo is_array($myarray) ? 'True':'False';
    

    sure that would be true, .


    You can access the subtotal column value without using foreach loop. Here is the code.

    $response = $client->orders->get();
    $subtotal = $response[0]->subtotal;
    

    If you would like to use foreach then you can access like this.

    foreach ( $client->orders->get() as $order ) {
     echo $order->order_number;
    }
    
    链接地址: http://www.djcxy.com/p/64870.html

    上一篇: 如何将字符串转换为stdClass对象为数组[PHP]

    下一篇: 来自API调用的PHP对象数组