Jump to content

Looping through an stdClass Array


m0rt1l

Recommended Posts

Hi im wondering if anyone could shed light on how to do this. I have an array below: ( codeigniter style )

 

Array ( [0] => stdClass Object ( [id] => 1 [cat_name] => Doo Range ) [1] => stdClass Object ( [id] => 2 [cat_name] => Com Range ) [2] => stdClass Object ( [id] => 3 [cat_name] => Master Range ) )

 

I need to loop through and pick out all cat names, at the moment using the code I have only returns one cat name.

 

$query = $this->db->query("SELECT * FROM fuel_product_cats");

 

foreach($query->result() as $rows)

{

$options = array($rows->id => $rows->cat_name);

}

 

// Check the array

print_r($options); ### ONLY ONE CAT NAME APPEARS IN THE ARRAY, NOT ALL 3 LIKE I WANT

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/264953-looping-through-an-stdclass-array/
Share on other sites

You are replacing the value in $options each time through the loop. You need to append them:

 

$options = array(); // Initialize the result array
foreach($query->result() as $rows)
{
  /* This would give you an array of arrays ...
    $options[] = array($rows->id => $rows->cat_name);
  */

  // But I suspect what you really want is a single-dimension keyed by ID
  $options[$rows->id] = $rows->cat_name;
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.