How to get data from array in object

29,434

Solution 1

As you can see by your output, object members are likely to be private (if you follow conventions, anyway you must prepend an underscore while calling them), so you're calling them the wrong way; This code works:

$this->_data->fields['province'][0];

You can see it in action here; I created a similar object, and using

$membership = new RSMembershipModelSubscribe();
echo $membership->_data->fields['province'][0];

outputs "Flevoland" as expected.

Solution 2

You can also use type casting.

$fields = (array) $this->data->fields;
echo $fields['province'][0];
Share:
29,434
Antoon Cusell
Author by

Antoon Cusell

Updated on July 09, 2022

Comments

  • Antoon Cusell
    Antoon Cusell almost 2 years

    I can't seem to get specific data from an array inside an object.

    $this->fields->adres gets the address correctly, but i can't get a level deeper.

    I've tried:

    $this->fields->province
    $this->fields->province->0
    $this->fields->province[0]
    

    And: (edit)

    $this->fields["province"][0]
    $this->fields['province'][0]
    $this->data->fields['province'][0]
    

    But it does not return anything while it should return "Flevoland".

    First part of the object print_r($this, TRUE) below:

    RSMembershipModelSubscribe Object
    (
        [_id] => 2
        [_extras] => Array
            (
            )
    
        [_data] => stdClass Object
            (
                [username] => testzz
                [name] => testzz
                [email] => [email protected]
                [fields] => Array
                    (
                        [province] => Array
                            (
                                [0] => Flevoland
                            )
    
                        [plaats] => tesdt
                        [adres] => test
    
    • Rene Pot
      Rene Pot over 12 years
      be consistent in language. Use 'city' and 'address' ;)
  • Rene Pot
    Rene Pot over 12 years
    unfortunately not. Fields is an array
  • r15habh
    r15habh over 12 years
    fixed it sec before comment -_-
  • Antoon Cusell
    Antoon Cusell over 12 years
    Thanks for your quick response guys, unfortunately, none of them gave back any result.. any other suggestions?
  • Antoon Cusell
    Antoon Cusell over 12 years
    Thanks for your quick response guys, unfortunately, none of them gave back any result.. any other suggestions?
  • Damien Pirsy
    Damien Pirsy over 12 years
    You were almost there, @Antoon :). Please consider marking this answer as "accepted" (the tick mark under the vote count) for future references; glad to have helped :)
  • Whetstone
    Whetstone over 12 years
    That really should have done it. Can you do a print_r on $this directly before running this line of code, then run it after? I'm suspecting there may be a different problem.
  • Mike Q
    Mike Q over 4 years
    Was going to mention this :-)