I have multiple rows getting returned from a database query.

I am able to get just a row at a time, but I want to put the rows in an array of objects like this:

$trailheads[] = new StdClass;
Loop
{
   $trailheads[] = $trailhead; // Put each object into the array of objects 
}

But when I try to loop through each array, I am having trouble extracting the values of each row. What is the right way to loop through the returned object and get the values?

The code that does not work is pretty basic:

$returned_obj->o->trailhead_name

But I am actually hoping be able to loop through each array element.

share|improve this question
  • 2
    Could you post the code that does not work? – stefgosselin Jun 3 '11 at 19:45
  • Post here normal code sigment, and colored it – azat Jun 3 '11 at 19:48
  • @stefgosselin Just edited my question with a small example – Genadinik Jun 3 '11 at 19:48
  • Please provide more code. You can't add elements to an object, just properties. – Philippe Gerber Jun 3 '11 at 19:49
  • The issue is not in the loop, there is no loop in your code example. From what I see your issue is before the loop! ;) – stefgosselin Jun 3 '11 at 19:53
up vote 0 down vote accepted

Maybe try casting to array in your for loop, this is untested and may not work as is but should get you on the right track:

foreach ($trailheads as (array) $key){

    // $key is now an array, recast to obj if you want  
    $objkey  = (object) $key;

}
share|improve this answer
  • Actually, for some reason, this gave an error: foreach ($trailhead_list->o as (array) $key) – Genadinik Jun 3 '11 at 20:00
  • Your outer variable was an array in your example, if $trailhead_list is your outer variable you need to use it as an array. – stefgosselin Jun 3 '11 at 20:07

i'm assuming your using mysql since you did not say...

you can use thsi function mysql_fetch_object()

<?php
$trailheads = array()

$result = mysql_query("select * from mytable");
while ($row = mysql_fetch_object($result, 'trailhead')) {
    $trailheads[] = $row;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.