Jump to content

Looping through PHP objects


Go to solution Solved by Muddy_Funster,

Recommended Posts

Hi,

I am trying to loop through using php inorder to get the elements

$names= $names>GetResult;

foreach ($names as &$name)
{
    echo $name->ID;

}

 

The above code gives me an error

Notice: Trying to get property of non-object

 

But if i try to access as below with the index number, it works.

foreach ($names as &$name)
{
    echo $name[0]->ID;

}

The problem with the above method is it will just give one, but i want to loop through and get all the contents.

 

I know its something really basic that i ma missing but would appreciate your help.

Many Thanks,

T

 

 

Link to comment
https://forums.phpfreaks.com/topic/300374-looping-through-php-objects/
Share on other sites

Hi,

 

I have just done print_r($names) and it returns back below.

 

$names= $names->GetResult;

print_r($names);

 

and it returns below.

 

stdClass Object ( [Reult] => Array ( [0] => stdClass Object ( [iD] => 1 [testid2] => 2 [TypeID] => 4 [Title] => test [Description] => test [Date] => 2016-01-07 )  [1] => stdClass Object ( [iD] => 2 [testid2] => 3 [TypeID] => 5 [Title] => test22 [Description] => test222 [Date] => 2016-01-07)

 

Thanks

Edited by tsdesai
  • Solution

So what you have is an object containing an array of objects, you need to iterate through each level.

so:

 

$nameObj = $names->GetResult;
foreach($nameObj as $nameArray){
  foreach($nameArray as $dataObj){
    echo $dataObj->ID;
  }
}
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.