6

I have an multiple array ($result) which has objects in it. The array was returned from a function (made by someone I can't communicate now).

When I test the array with print_r($result[0]), it turns out to have embedded objects.

ABC Object ( 
    [p1] => P1 Object ( 
        [p1-1] => P1_property1 
        [p1-2] => P1_property2 
        [p1-3] => P1_property3
    ) 
    [p2] => ABC_property2 
    [p3] => ABC_property3 
    [p4] => ABC_property4
)

How can I fetch the Strings "P1_property1" to "P1_property3" and "ABC_property2" to "ABC_property4"?

I'm new to PHP, waiting for help!

5
  • and it doesn't work to use $result[0]['p1']['p1-1']? Commented May 10, 2012 at 21:42
  • @hovmand: Not if it's an object, and not an array. It'd have to be $result[0]->p1->{'p1-1'} Commented May 10, 2012 at 21:43
  • @Rocket: Of course, will this work too? $result[0]::p1::p1-1, and why the brackets around p1-1? Commented May 10, 2012 at 21:45
  • 1
    @hovmand: That's not what :: is used for, it's for static properties. The brackets are because ->p1->p1-1 would be a problem because of the '-'. Commented May 10, 2012 at 21:46
  • @Rocket Thanks a lot!! this work, also, $result[0]->{'p2'} is for the properties not embedded in an object. Thanks for the clever tip. Commented May 10, 2012 at 23:40

3 Answers 3

5

Sounds like you want get_object_vars(), which will return an array of accessible properties.

class foo {
  public $bar = "foo";
  private $bor = "fizz";
}

$properties = get_object_vars( new foo() );

print_r( $properties );

Which outputs:

Array
(
    [bar] => foo
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! but I wanted to just to get the string of the properties. the comments below my original question works great.
3

Try using this to figure out what the contents of those variables are:

var_dump(get_object_vars($result[0]));

1 Comment

Thanks! but I wanted to just to get the string of the properties. the comments below my original question works great.
1
This function return all the properties in a class

function get_object_public_vars($object) {
    return get_object_vars($object);
}

1 Comment

This has been given in the other answers already - what's the need of duplicating them?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.