CodeIgniter Forums
Accessing Objects - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Accessing Objects (/showthread.php?tid=39557)



Accessing Objects - El Forum - 03-14-2011

[eluser]Unknown[/eluser]
Hi All,
I'm a relatively novice developer but I'm really enjoying using CI at the moment and have been able to a lot by using the resources on the forums and wikis. However, I've hit my first problem which I haven't been able to find the answer to...

I'm passing an array of objects to a view in order to display elements in a table with some other information.

Code:
Array ( [0] => stdClass Object ([taskId] => 1 [taskEffort = 10) [1] => stdClass Object ([taskId] => 2 [taskEffort] = 5))

I would like to access taskEffort attribute for a given value of 'taskId' which is already defined. Any ideas how I would do this?


Many Thanks.


Accessing Objects - El Forum - 03-15-2011

[eluser]n0xie[/eluser]
You could do it with a foreach loop like this.
Code:
foreach ($name_of_array as $object)
{
  if ($object->taskId == $your_defined_taskId) { // do stuff }
}

Assuming the array of objects came from a database I would rewrite the structure so that the array key corresponds with the taskId. That way you can skip the loop:

Code:
// structure, the key 1 & 2 correspond to the taskId 1 & 2
array
  1 =>
    object(stdClass)[14]
      public 'taskEffort' => int 10
  2 =>
    object(stdClass)[15]
      public 'taskEffort' => int 5

// so to get the object with taskId you simply do it like this:
echo $name_of_array[2]->taskEffort;



Accessing Objects - El Forum - 03-16-2011

[eluser]Unknown[/eluser]
Many thanks n0xie, much appreciated.