为了账号安全,请及时绑定邮箱和手机立即绑定

php中的组json嵌套对象

php中的组json嵌套对象

PHP
浮云间 2023-07-01 15:08:25
我有一个 json 响应,如下所示:$response ='[    {        "userSummaries": [            {                "id": "9910",                "status": "Active",                "name": "Jhon"            }        ]    },    {        "userSummaries": [            {                "id": "8754",                "status": "Active",                "name": "Jane"            }        ]    }]';我想用userSummaries这个 php 代码将其分组:$myArr = json_decode($response, true);      $result_arr = [];        array_walk($myArr,function($v,$k) use (&$result_arr){       $result_arr[key($v)] = $v[key($v)];     });       echo json_encode($result_arr);并且响应只返回一个数据:{"userSummaries":[{"id":"8754","status":"Active","name":"Jane"}]}是否可以得到这样的输出响应?:{"userSummaries":[{"id":"9910","status":"Active","name":"Jhon"}, {"id":"8754","status":"Active","name":"Jane"}, ]}通过网络尝试过,但没有找到解决方案这是我的脚本: https: //3v4l.org/tVkK5也尝试过这个:$class_array = array();foreach ($myArr as $sa) {    $class_array[$sa['userSummaries']][] = array('name' => $sa['name']);}但返回:Notice: Undefined index: name in /in/hvSFC on line 28Warning: Illegal offset type in /in/hvSFC on line 28Notice: Undefined index: name in /in/hvSFC on line 28Warning: Illegal offset type in /in/hvSFC on line 28[]需要帮忙
查看完整描述

1 回答

?
哈士奇WWW

TA贡献1799条经验 获得超6个赞

你很接近。您只需要在每个循环中引用键和第一个userSummaries,而不是使用整个...


$myArr = json_decode($response, true);

$result_arr = ["userSummaries"=>[]];

foreach($myArr as $user) {

    $result_arr["userSummaries"][] = $user['userSummaries'][0];

}

echo json_encode($result_arr);

结果是:


{"userSummaries":[

    {"id":"9910","status":"Active","name":"Jhon"},

    {"id":"8754","status":"Active","name":"Jane"}

]}

如果您预见每个中的 userSummaries 本身将有多个用户......那么这将起作用:


$response ='[

    {

        "userSummaries": [

            {

                "id": "9910",

                "status": "Active",

                "name": "Jhon"

            }

        ]

    },

    {

        "userSummaries": [

            {

                "id": "8754",

                "status": "Active",

                "name": "Jane"

            },

            {

                "id": "5421",

                "status": "Active",

                "name": "Bob"

            }

        ]

    }

]';


$myArr = json_decode($response, true);

$result_arr = ["userSummaries"=>[]];

foreach($myArr as $usergroup) {

    foreach($usergroup['userSummaries'] as $user) {

        $result_arr["userSummaries"][] = $user;

    }

}

echo json_encode($result_arr);

结果是:


{"userSummaries":[

    {"id":"9910","status":"Active","name":"Jhon"},

    {"id":"8754","status":"Active","name":"Jane"},

    {"id":"5421","status":"Active","name":"Bob"}

]}


查看完整回答
反对 回复 2023-07-01
  • 1 回答
  • 0 关注
  • 126 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信