문제

I am working response from an API which returns data in JSON in a fairly straight forward structure. Pseudo structure is best represented as:

services -> service -> options -> option -> suboptions -> option

As this is decoded JSON, all of these are stdClass objects. I have a number of foreach statements iterating through the various services and options, which all work without issue. However, when I use a foreach statement at the suboption level, the object is serialized into a string. For your information suboptions has a structure like this.

[suboptions] => stdClass Object
 (
    [option] => stdClass Object
        (
            [code] => SOME_CODE
            [name] => Some Name
        )

 )

When using a foreach such as this (where $option is an option in services -> service -> options -> option):

foreach($option->suboptions->option as $suboption) {
  print_r($suboption);
}

It outputs

SOME_CODESome Name

Not the expected

stdClass Object
  (
     [code] => SOME_CODE
     [name] => Some Name
  )

I am not aware of any reasons foreach would do this in terms of depth or other conditions. I've tried everything I can think of and searched through SO and can't find any case of this happening. If anyone has any ideas I'd love to hear them! Cheers.

Apologies if it has been answered elsewhere or I am missing something obvious. If I have, it has escaped me thus far.

Edit: For those asking it is indeed the AusPost PAC API. Changing over from the DRC as it is being removed ~2014.

도움이 되었습니까?

해결책 2

I'm assuming this is from a response from the Australia Post postage calculation API. This API makes the horrible decision to treat collection instances with only one item as a single value. For example, service -> options -> option may be an array or it may be a single option.

The easiest way I've found to deal with this is cast the option to an array, eg

$options = $service->options->option;
if (!is_array($options)) {
    $options = array($options);
}

// now you can loop over it safely
foreach ($options as $option) { ... }

You would do the same thing with the sub-options. If you're interested, I've got an entire library that deals with the AusPost API, using Guzzle to manage the HTTP side.

다른 팁

I can't comment, because I don't have that amount of reputation, but I'll try to answer...

I'm assuming you want to remove the stdClass from the PHP array?

If so, then make sure you are using true when decoding the JSON.

Example: $array = json_decode($json, true);

For more information on stdClass, see this SO post: What is stdClass in PHP?

Again, forgive me if I'm misinterpreting your question, I just wish I could comment...

The values of the last object are not arrays so you would need both the key and value.

foreach($option->suboptions->option as $key => $value) {
  echo '<p>KEY:'.$key.' VALUE:'.$value.'</p>';
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top