m0rt1l Posted June 28, 2012 Share Posted June 28, 2012 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. Quote Link to comment https://forums.phpfreaks.com/topic/264953-looping-through-an-stdclass-array/ Share on other sites More sharing options...
DavidAM Posted June 28, 2012 Share Posted June 28, 2012 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; } Quote Link to comment https://forums.phpfreaks.com/topic/264953-looping-through-an-stdclass-array/#findComment-1357753 Share on other sites More sharing options...
m0rt1l Posted June 28, 2012 Author Share Posted June 28, 2012 Of course it is! Doh, sometimes it needs someone to point out the obvious....Many thanks Quote Link to comment https://forums.phpfreaks.com/topic/264953-looping-through-an-stdclass-array/#findComment-1357755 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.