2

I have a json respond that I want to check and return values accordingly: the Json code is:

{
 "success": "true",
 "result": "ok"
}

And I need to check the success status and return an array to the controller accordingly.

I was trying to decode and ask questions on the value as follow:

$obj = json_decode($response,true);
    if ($obj['success'] =='true')
      return array(
        'error' => 0,
        'msg' => sprintf("successfully")
      );

I am not sure what i am doing wrong since I can't get the 0 in the error on array returns.

There is another json code that I need to deal with and it is this:

Negative Response:

{
“success” : “false” ,
“error”:{
        “code”:"MANDATORY_FIELDS_MISSING",
        "message”: “Phone number is a mandatory field"
    }
}

The same goes with this.

I would be happy if you couls assist me with gettin it to work properly. Thank you. Arye

2
  • Are you sure the JSON contains the string "true", not the boolean true? Commented May 6, 2015 at 18:01
  • Your negative response is not valid JSON. You have to use ASCII double quotes, not curly quotes, around strings. Is that a copying error? Commented May 6, 2015 at 18:02

2 Answers 2

1

Actually your code working fine. You are confused with printing and returning. Please check this:--

<?php 

$response = '{"success": "true","result": "ok"}';
$obj = json_decode($response,true);
    if ($obj['success'] =='true')
      print_r (array(
        'error' => 0,
        'msg' => sprintf("successfully")
      ));
?>

Output:-- http://prntscr.com/729h1o

So i think instead of return you need to print it out.

And you can use var_dump as well as echo <pre/>;print_r(your array inside if) just for look a bit good.

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

1 Comment

Solved! Thank you all so much :) I was there and I didn't realized that. thank you all for helping.
1

code:

$json = '
{
 "success": "true",
 "result": "ok"
}';

$obj = json_decode($json, true);


if ($obj['success'] == 'true')
    var_dump(array(
        'error' => 0,
        'msg' => 'successfully'
    ));

output:

array(2) {
  'error' =>
  int(0)
  'msg' =>
  string(12) "successfully"
}

When you run the code above, do you get the same output I see?

1 Comment

Solved! Thank you all so much :) I was there and I didn't realized that. thank you all for helping.

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.