开发者

Returning an array of objects in a php function

开发者 https://www.devze.com 2023-03-11 09:57 出处:网络
I have mul开发者_如何学Gotiple 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:

I have mul开发者_如何学Gotiple 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.


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;

}


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消