简体   繁体   中英

Accessing object element by index

I'm using eBay API which returns:

DTS\eBaySDK\Types\RepeatableType Object
(
    [data:DTS\eBaySDK\Types\RepeatableType:private] => Array
        (
            [0] => 60
        )

    [position:DTS\eBaySDK\Types\RepeatableType:private] => 0
    [class:DTS\eBaySDK\Types\RepeatableType:private] => DTS\eBaySDK\Shopping\Types\NameValueListType
    [property:DTS\eBaySDK\Types\RepeatableType:private] => Value
    [expectedType:DTS\eBaySDK\Types\RepeatableType:private] => string
)

... and if I try to access it like so:

echo $ItemSpecific->Value->{0};

... I get this error:

Notice: Undefined property: DTS\\eBaySDK\\Types\\RepeatableType::$0 in ...

Since DTS\\eBaySDK\\Types\\RepeatableType implements ArrayAccess interface, you can access the items of the private $data array as follows:

foreach ($ItemSpecific as $item) {
  var_dump($item);
}

or by index: $ItemSpecific[0] . But it's more likely that you need to iterate the object in one way or another.

I use to run into this same issue. The problem is that the information you want to parse out appears to be a private property of an object. Private properties of an object are restricted to the object. Standard practice of getting a private property to call a public function with in the object to output the value. It's likely that such a function does not exist and therefore you cannot parse the information.

These rules, however, will only apply with in the realm of PHP. If you change this information into a static value, these rules will no longer apply.

<?php
function parse($obj, $start="[", $end = "]"){
    $string = json_encode($obj);
    $s = strpos($string, $start) + 1;
    $e = strpos($string, $end);
    $diff = $e - $s;
    return substr($string, $s, $diff);
}

  echo parse($ItemSpecific->Value);

Now I do not have a sample of your exact API result so you might have to change the parameters a bit, but this general idea should solve your problem.

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