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

数组 相同键值合并问题

WBOY
WBOYOriginal
2016-06-23 13:04:54913browse

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

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


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


回复讨论(解决方案)

$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);

Statement:
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