获取对象的字段

时间:2017-11-16 09:53:11

标签: php laravel

我有下面的对象

{
"user": "58a9bf92e0f78000055dd932",
"type": "template_created",
"count": 2
}

我需要得到用户'字段,..->type返回" template_created"并且..->count给出了它的值,但..->user返回null。顺便提一下,这些对象来自mongodb聚合框架。

4 个答案:

答案 0 :(得分:1)

它看起来像你的对象 json-encoded 。这意味着,您可以使用本机php函数json_encode()json_decode()来处理它们。在您的示例中,您可以通过调用

来反序列化对象
$obj = json_decode($str);

$str是您在上面显示的数据。现在,您可以使用标准的php访问方法(如

)访问此对象的字段
$type = $obj->type;

希望这有帮助!

答案 1 :(得分:1)

使用此代码

$data = json_decode($data); //where $data contain the json
$data->user;

答案 2 :(得分:1)

请勿忘记在json_decode之后检查错误,如下所示:

$payload = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException('Invalid JSON.');
}
// also you cah check this
if (property_exists($payload, 'user')) {
    var_export($payload->user);
}

答案 3 :(得分:0)

您可以通过两种方式解决: -

$data = '{
    "user": "58a9bf92e0f78000055dd932",
    "type": "template_created",
    "count": 2
    }';
$objectdata = json_decode($data); //stclassobject
echo $objectdata->count;
  --------OR-------
$arraydata= json_decode($data,true); //convert to array
echo $arraydata['count'];

希望它能够结束!