php中的组json嵌套对象

我有一个 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 28


Warning: Illegal offset type in /in/hvSFC on line 28


Notice: Undefined index: name in /in/hvSFC on line 28


Warning: Illegal offset type in /in/hvSFC on line 28

[]

需要帮忙


浮云间
浏览 127回答 1
1回答

哈士奇WWW

你很接近。您只需要在每个循环中引用键和第一个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"}]}
打开App,查看更多内容
随时随地看视频慕课网APP