简体   繁体   中英

reading json with object

I decoded an incoming string via POST in two JSON and I'm trying to read it and save the keys in vars. these are the arrays:

$infos = $_POST;

$orderInformation['orderInfo'] = json_decode($infos['orderinf']);

$orderItensInformation['orderItensInfo'] = json_decode($infos['orderitensinf']);

This is what var_dump returns of $orderInformation :

array(1) {
  ["orderInfo"]=>
    object(stdClass)#1 (9) {
      ["customer_fone"]=>
      string(10) "5554120082"
      ["neighborhood"]=>
      string(4) "aaaa"
      ["order_price"]=>
      int(45)
      ["payment_method"]=>
      string(8) "CASH"
      ["customer_email"]=>
      string(19) "abc@def.com"
      ["street"]=>
      string(14) "Unknown street"
      ["number"]=>
      string(3) "111"
      ["order_date"]=>
      object(stdClass)#2 (5) {
        ["day"]=>
        int(3)
        ["month"]=>
        int(11)
        ["time"]=>
        int(1)
        ["year"]=>
        int(2013)
        ["minute"]=>
        int(24)
      }
      ["customer_name"]=>
      string(6) "Noname"
    }
}

The question is how do I get the information inside the object? I tried to use foreach:

foreach($orderInformation->orderInfo as $oi) {
      $fone = $oi->customer_fone;
      $nbh = $oi->neighborhood;
       .
       .
       .
}

But didn't work. The vars were empty.

No need for a loop, unless you have multiple orders in this array

$orderInformation['orderInfo'] is your object

echo $orderInformation['orderInfo']->customer_fone;
// Should return 5554120082

For a neater approach, try

$x = $orderInformation['orderInfo'];
echo $x->customer_fone;

The big err in your code.

$orderInformation->ordeInfo does not exist as a property like you are calling it.

$orderInformation['orderInfo']

From the manual , return will be an object unless your second parameter passed into it is set to true, which will return an associative array (might be more suitable for you in this case):

$orderInformation['orderInfo'] = json_decode($infos['orderinf'], true);

$orderItensInformation['orderItensInfo'] = json_decode($infos['orderitensinf'], true);

foreach($orderInformation['orderInfo'] as $oi) {
      $fone = $oi['customer_fone'];
      $nbh = $oi['neighborhood'];
       .
       .
       .
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM