Home > Backend Development > PHP Tutorial > 数组 相同键值合并问题

数组 相同键值合并问题

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-23 13:04:54
Original
935 people have browsed it

下面格式的数组,需要合并相同clientId的roleId。

$data =  '[    {      "ClientId": 0,      "RoleId": 2    },    {      "ClientId": 1,      "RoleId": 1    },    {      "ClientId": 1,      "RoleId": 4    }  ]';$data = json_decode($data);
Copy after login


合并后的
$data =  '[    {      "ClientId": 0,      "RoleId": [2]    },    {      "ClientId": 1,      "RoleId": [1,4]    }  ]';$data = json_decode($data);
Copy after login


回复讨论(解决方案)

$data = json_decode($data, true);$arr = array();foreach($data as $itm) {	$arr[$itm['ClientId']]['ClientId'] = $itm['ClientId'];	$arr[$itm['ClientId']]['RoleId'][] = $itm['RoleId'];}$arr = array_values($arr);
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template