0

I have some JSON, if I var_dump the output looks like:

var_dump( $oJSON->{$oQ->sQuestionName} );

object(stdClass)[14]
  public 'Lease' => boolean true

I would like to retrieve 'Lease' as a string.

I've tried casting it:

(string)$oJSON->{$oQ->sQuestionName}

but it returns an E_RECOVERABLE:

E_RECOVERABLE_ERROR Error: Object of class stdClass could not be converted to string

The following works, however I feel there must be a better way?

array_shift(array_values(array_keys(get_object_vars($oJSON->{$oQ->sQuestionName}))));

N.B. I can't use to use the following due to compatability issues

array_keys(get_object_vars($oJSON->{$oQ->sQuestionName}))[0]
2
  • 1
    I can't use to use the following due to compatability issues just split it into two lines. Commented Nov 29, 2016 at 16:25
  • yeah I could do that. Assign to a var, then go to first pos. However it feels there must be some other method? Commented Nov 29, 2016 at 16:26

3 Answers 3

1

Use ReflectionClass::getProperties() to get a list of the object's properties.

$reflect = new ReflectionClass($foo);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED);
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert your desired object to an array first

   $array = (array) $oJSON->{$oQ->sQuestionName};

Then you can take its first element's key

   echo key($array);  // Should say Lease

Fiddle

Comments

0

You can use json_decode with second parameter true

For example:

$str = '{"0":{"id":"123","name":"Title"}}';
var_dump(json_decode($str,true));

So, you will have an array with string objects.

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.