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

Link to comment
Share on other sites

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.