Welcome Guest, Not a member yet? Register   Sign In
Looking for an explanation of stdClass Object
#1

[eluser]caperquy[/eluser]
I am currently studying codeigniter samples. It appears that the result of MySQL requests returns something like this :

Array (
  • =>Array([0]=>stdClass Object([id]=>9 [name]=>Anna [email]=>anna@Anna.com)[1] =>stdClass Object([id]=>5[name]=>Bill[email]=>[email protected])[2]=>stdClass Object([id]=>1 [name]=>Bob [email]=>bob@bob.com)[3]=>stdClass Object([id]=>10[name]=>Hellen [email]=>[email protected]) [4]=>stdClass Object([id]=>7 [name]=>John [email]=>john@john.com)))

    Question 1 : I am looking for an explanation of what a stdClass Object is, as well as its
    utility ?
    Question 2 : how to access a specific element (for instance all names) of such complex
    array ?

    Many thanks for help.
#2

[eluser]mddd[/eluser]
1. StdClass means an object that has no specific class. It is "just a basic object". Every object in php start out from a 'basic object' which is then extended with all the characteristics of the specific class that it is an instance of (like Model, Controller, etc).

2. A mysql result is simply a list of objects. Each object is one row from the database result. If you wanted to display all the names, you would do:
Code:
foreach ($list as $item)
{
  echo 'name: ' . $item->name;
}
If you feel more comfortable with arrays, you can always use result_array() instead of result(). That will give a list of arrays instead of a list of objects. Then you could do:
Code:
foreach ($list as $item)
{
  echo 'name: ' . $item['name'];
}
#3

[eluser]yohanip[/eluser]
hints :
if you see using a var_dump : let's break them so it would be better to see the structure..
Code:
Array ([list]=>
Array(
   [0]=>stdClass Object(
      [id]=>9
      [name]=>Anna
      [email]=>[email protected]
      )
   [1] =>stdClass Object(
      [id]=>5
      [name]=>Bill
      [email]=>[email protected]
      )
   [2]=>stdClass Object(
      [id]=>1
      [name]=>Bob
      [email]=>[email protected]
      )
   [3]=>stdClass Object(
      [id]=>10
      [name]=>Hellen
      [email]=>[email protected]
      )
   [4]=>stdClass Object(
      [id]=>7
      [name]=>John
      [email]=>[email protected]
      )
   )//this is the end of your array
)//this is the end of $list
there you see a list of objects in array where each item is an object of stdClass type
accessing them, use a simple iterator such as foreach

as for the example above :
Code:
foreach($array_list as $item)

and if you see [0]=>stdClass Object([id]=>9 [name]=Anna ... ...
to get id use
Code:
$item->id

to get name use
Code:
$item->name
#4

[eluser]caperquy[/eluser]
Many thanks for these clear replies. I think that I will now manage with no problem.




Theme © iAndrew 2016 - Forum software by © MyBB