使用PHP检查Json数组的值

时间:2015-05-06 17:59:15

标签: php arrays json

我有一个json响应,我想检查并相应地返回值: Json代码是:

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

我需要检查成功状态并相应地将数组返回给控制器。

我正在尝试解码并询问有关价值的问题如下:

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

我不确定我做错了什么,因为我无法在数组返回的错误中得到0。

还有一个我需要处理的json代码,就是这样:

否定回应:

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

同样如此。

如果你帮助我开始正常工作,我会很高兴。 谢谢。 阿里耶

2 个答案:

答案 0 :(得分:1)

其实你的代码工作正常。您对打印和返回感到困惑。 请检查: -

<?php 

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

输出: - http://prntscr.com/729h1o

所以我认为不是返回,而是需要将其打印出来。

你可以使用var_dump以及echo <pre/>; print_r(你的数组在if中)只是为了看起来有点好。

答案 1 :(得分:1)

代码:     

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

$obj = json_decode($json, true);


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

输出:

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

当你运行上面的代码时,你看到的输出是否相同?

相关问题