1

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 Answers 3

3

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

$options[0]->option_name
Sign up to request clarification or add additional context in comments.

1 Comment

Ahm thanks. You get the points, since you where the first to answer :)
3

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;

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.