0

How can i loop into the below php object and pull propery value (name, surname, city, country) if a certain property value (id) is given by me.

$users = (object) array( 'id' => '753', 'firstname' => 'trevor', 'lastname' => 'bean', 'address' => array( (object) array( 'country' => 'Romania' 'city' => 'Iasi' ) ) ) (object) array( 'id' => '754', 'firstname' => 'ben', 'lastname' => 'stone', 'address' => array( (object) array( 'country' => 'Hungary' 'city' => 'Budapest' ) ) ); 

I have tested:

 foreach ($users as $user1) { if ($user1->id=== '754') { echo $user1->firstname break; } } 

And it returns trevor - the firstname of id 753 instead of the firstname ben of the requested id 754

1
  • 1
    your $users variable won't even compile to begin with, where are you getting your object from? some JSON result or what? Perhaps if you give us more information about where your data comes from and how it comes we might be able to give you a simpler solution... Commented Jan 26, 2015 at 20:59

3 Answers 3

1

The code you posted is invalid and will not compile. I allowed myself to make some assumptions how to correct it:

$users = array( (object)array( 'id' => '753', 'firstname' => 'trevor', 'lastname' => 'bean', 'address' => array( (object)array( 'country' => 'Romania', 'city' => 'Iasi' ) ) ), (object)array( 'id' => '754', 'firstname' => 'ben', 'lastname' => 'stone', 'address' => array( (object)array( 'country' => 'Hungary', 'city' => 'Budapest' ) ) ) ); foreach ($users as $user1) { if ($user1->id=== '754') { echo $user1->firstname; break; } } 

Now it works as you request.

Note that I wrapped your objects with array.

Sign up to request clarification or add additional context in comments.

Comments

0

Your PHP has some obvious syntax errors (missing ; and ,) and I think you want the $users variable to be an array of user objects, not an object. Your code should probably look something like this:

$users = array( (object) array( 'id' => '753', 'firstname' => 'trevor', 'lastname' => 'bean', 'address' => array( (object) array( 'country' => 'Romania', 'city' => 'Iasi' ) ) ), (object) array( 'id' => '754', 'firstname' => 'ben', 'lastname' => 'stone', 'address' => array( (object) array( 'country' => 'Hungary', 'city' => 'Budapest' ) ) ) ); foreach ($users as $user1) { if ($user1->id=== '754') { echo $user1->firstname; break; } } 

And it retuns the ben user as expected:

Comments

0

I think you want PHP's get_object_vars(). It will return the object's accessible (public, in this case), non-static properties in an associative array:

foreach (get_object_vars($users) as $user1) { if ($user1->id=== '754') { echo $user1->firstname; break; } } 

You'll also want to fix the multiple places where you have missing ,s and ;s.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.