tags:

views:

33

answers:

3

The following code:

      $options = $value[$i]['options'];
      print_r($options);

outputs the following result:

Array ( 
  [0] => stdClass Object ( 
        [id] => 1 
        [field_id] => 1 
        [option_name] => I'm a normal user ) 
  [1] => stdClass Object ( 
        [id] => 2 
        [field_id] => 1 
        [option_name] => Store owner ) 
  [2] => stdClass Object ( 
        [id] => 3 
        [field_id] => 1 
        [option_name] => Brand owner ) 
  [3] => stdClass Object ( 
        [id] => 4 
        [field_id] => 1 
        [option_name] => Designer ) 
)

So why can't I output "I'm a normal user" using echo $options[0]["option_name"] ?

My plan is to output id and option_name using a foreach loop:

  foreach ($options as $option)
  {
    echo "<option value='".$option["id"]."'>".$option["option_name"]."</option>";
  } 

This should be easy.... but I'm fumbling :(

+3  A: 

Try using this in the foreach

$option->option_name;
$option->id;

$options is actually an object. Thats why you see it is an instance of stdClass. Each value in that class is accessed through the -> accessor.

BTW, you can access it regularly like this:

$options[0]->option_name;
$options[0]->id;
Chacha102
+3  A: 

The second level is not an array but an object. This would be correct:

$options[0]->option_name
Tomas Markauskas
Ahm thanks. You get the points, since you where the first to answer :)
Steven
A: 

Do keep in mind if you assign one of those values to a new variable, you're getting an object, not a string. You can fix that by doing something like this:

$string = (string)$options[0]->option_name;

This isn't an issue if you're simply outputting the way your example shows, but would matter more if you were using the value as, say, an array key. Example:

$array[$options[0]->id] == $array[1]; // FALSE!!
$array[(string)$options[0]->id] == $array[1] // True.
Erik