-1

I am parsing a JSON being posted from another website and one of the nodes has a child.

$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON); //convert JSON into object

$order_number = $input->{'order_no'};
$name = $input->{'name'};
$street_address = $input->{'address_1'};
$city =$input->{'city'};
$state = $input->{'region'} ;
$zip = $input->{'postal_code'};

I am being able to read all the values. However, the product section has the format

<items>
    <product_code></product_code>
    <product_name></product_name>
</items>

I am trying to read it as

$product_id = $input->{'items'}{'product_code'};
$product_description = $input->{'items'}{'product_name'};

But I am getting no data in my variables. What is the correct syntax?

Thanks.

Edit: The JSON output

object(stdClass)#1 (20) {
  ["test_order"]=>
  string(1) "Y"
  ["shop_no"]=>
  string(6) "142319"
  ["order_no"]=>
  string(12) "TU5495467701"
  string(5) "Smith"
  ["city"]=>
  string(5) "Bosei"
  ["postal_code"]=>
  string(6) "123456"
  ["order_total"]=>
  string(5) "39.00"
  ["country"]=>
  string(2) "HK"
  ["telephone"]=>
  string(8) "12345678"
   ["pay_source"]=>
  string(2) "CC"
  ["base_currency"]=>
  string(3) "USD"
  ["items"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (9) {
      ["product_price"]=>
      string(5) "39.00"
      ["product_name"]=>
      string(12) "Abcd Product"
      ["product_code"]=>
      string(8) "142319-1"
    }
  }
  ["first_name"]=>
  string(4) "John"
}
4

4 回答 4

1

正如你所写:

["items"]=>
  array(1) {
    [0]=>
    object(stdClass)#2 (9) {
      ["product_price"]=>
      string(5) "39.00"
      ["product_name"]=>
      string(12) "Abcd Product"
      ["product_code"]=>
      string(8) "142319-1"
    }
  }

items元素是一个数组,包含多个对象,因此您必须使用以下语法:

$product_id = $input->items[0]->product_code;
$product_description = $input->items[0]->product_name;

而且,如果items超过一个,你应该使用一个循环:

for ($i = 0; $i < count($input->items); $i++) {
    $product_id = $input->items[$i]->product_code;
    $product_description = $input->items[$i]->product_name;
}
于 2013-06-01T07:31:39.047 回答
1
$product_id = $input->items[0]->product_code;

尽管您更可能希望循环$input->items不是直接访问第一个索引。

于 2013-06-01T07:32:41.857 回答
0

我不舒尔,但我认为您可以将其用作数组并执行以下操作:

$product_id = $input['items']['product_code'];
$product_description = $input['items']['product_name'];
于 2013-06-01T07:24:08.383 回答
-2

在 php json_decode 返回一个数组。因此,您应该能够像访问数组值一样访问它。

$product_id = $input['items']['product_code'];

于 2013-06-01T07:24:59.617 回答