【问题标题】:accessing a json.parse multidimensional array php访问 json.parse 多维数组 php
【发布时间】:2017-11-24 22:29:41
【问题描述】:

我有以下 json :-

{
    "firstName": "Jhon",
    "lastName": "Doe",
    "username": "jhon",
    "avatar": "localhost/uploads/avatars/default.jpg",
    "language": "ar",
    "birth_date": "2017-11-22 00:00:00",
    "weight_chart": [],
    "health_status": {
        "id": 130,
        "user_id": 258,
        "weight": 95,
        "height": 171,
    },

上面的json我解码了

$user = json_decode($response);

现在我可以使用以下方法打印名字: $user->名字

我的问题是:-

  • 我可以在不解码的情况下访问 json 值吗?
  • 如何访问“health_status”值 id、体重...?

【问题讨论】:

    标签: php arrays json multidimensional-array


    【解决方案1】:

    你的 json 格式不正确,试试这个结构:

    $str = '{
        "firstName": "Jhon",
        "lastName": "Doe",
        "username": "jhon",
        "avatar": "localhost/uploads/avatars/default.jpg",
        "language": "ar",
        "birth_date": "2017-11-22 00:00:00",
        "weight_chart": [],
        "health_status": {
            "id": 130,
            "user_id": 258,
            "weight": 95,
            "height": 171
        }
    }';
    
    $obj = json_decode($str);
    echo $obj->firstName.' - ';
    echo $obj->health_status->id.' - ';
    echo $obj->health_status->weight; 
    

    回复:Jhon - 130 - 95

    【讨论】:

    • 我得到的 json 来自一些 api web 服务而不是 json 文件,我无法控制 json 的结构。
    • @user2873860 您在问题中的 JSON 文档格式不正确。如果它只是一个错字,因为你是手写/编辑的,你应该承认/修复它,这样每个人都可以继续前进。
    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2013-06-12
    • 2013-08-25
    • 1970-01-01
    • 2014-04-15
    • 2013-09-01
    • 1970-01-01
    相关资源
    最近更新 更多