0

I am getting following result from database:

stdClass Object ( [risk_challenge] => ["dfsgdfgdgdf","dfgdfgdfg","dfgdfgdfgdf"] ) 

When I tried to decode it with following function:

$result = json_decode($result,true);

I got this error:

Message: json_decode() expects parameter 1 to be string, object given
3
  • first check your json. is it valid? Commented Oct 14, 2014 at 10:17
  • If it's an object, you've already decoded it. An instance of stdClass is a bona-fide PHP object, which you can iterate over, or access its members directly ($obj->risk_challenge[0], for example) Commented Oct 14, 2014 at 10:18
  • You got your answer in your error message. You need to get string from database result to decode it, and you are giving object to it instead of string. Commented Oct 14, 2014 at 10:22

2 Answers 2

1

What you have is a valid object, there's nothing JSON about it, it's an instance of the core stdClass class of PHP. If you want to use it (for example get list the risk_challenge values) simply write:

foreach ($obj->risk_challenge as $value)
    echo ' *> ', $value, PHP_EOL;

Job done.
If you want to convert the object to an associative array, you have 2 options:

$array = (array) $object;//a simple cast
$array = json_decode( //decode with assoc argument = true
    json_encode(// but first encode it
        $object
    ), true);

Why would you use the second version instead of the cast? simple: A cast is shallow (if any of the properties/keys contains another object, it will not be cast to an associative array, but it'll remain an object. json_decode does work recursively. In your case, though, I'd stick to the cast.

Sign up to request clarification or add additional context in comments.

2 Comments

how to call bootstrap modal in codeigniter controller function
@kalavathi: That's a different question all together, and probably one that has already been asked (or the answer to which is easily found in the manual).
0

I think you want to encode in json it is already decoded

use json_encode to encode

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.