php - PHP数组到指定的json结构
问题描述
我需要得到一个 JSON 结构如下:
{
"emails": [
{
"sender": "shihas@abc.com",
"unread_count": 2,
"items": [
{
"id": "89",
"email": "shihas@abc.com",
"read": "0",
},
{
"id": "32",
"email": "shihas@abc.com",
"read": "0",
}
]
},
{
"sender": "marias123@gmail.com",
"unread_count": 0,
"items": [
{
"id": "2",
"email": "marias123@gmail.com",
"read": "1",
}
]
},
{
"sender": "gutar4320@hotmail.com",
"unread_count": 1,
"items": [
{
"id": "1",
"email": "gutar4320@hotmail.com",
"read": "0",
}
]
}
]
}
数组($hire_email):
在下面的数组中,我需要根据email
. 并数数。未读消息(即已读 = 0)。
Array
(
[0] => Array
(
[id] => 89
[email] => shihas@abc.com
[read] => 0
)
[1] => Array
(
[id] => 32
[email] => shihas@abc.com
[read] => 0
)
[2] => Array
(
[id] => 2
[email] => marias123@gmail.com
[read] => 1
)
[3] => Array
(
[id] => 1
[email] => gutar4320@hotmail.com
[read] => 0
)
)
以下是用于维护 JSON 结构的代码片段。
foreach($hire_email as $val) {
if($val['read']==0){ $count++; }else{ $count = 0;}
$hire_group_email[$val['email']]['sender'] = $val['email'];
$hire_group_email[$val['email']]['unread_count'] = $count;
$hire_group_email[$val['email']]['items'][] = $val;
}
$output["emails"][] = $hire_group_email;
echo json_encode($output);
解决方案
这应该可以解决问题。
$hire_email =array(
array(
"id" => "89",
"email" => "shihas@abc.com",
"read" => "0"
),
array
(
"id" => "32",
"email" => "shihas@abc.com",
"read" => "0"
),
array
(
"id" => "2",
"email" => "marias123@gmail.com",
"read" => "1"
),
array
(
"id" => "1",
"email" => "gutar4320@hotmail.com",
"read" => "0"
)
);
$tmp = array();
foreach($hire_email as $arg)
{
$tmp[$arg['email']][] = $arg;
}
$output = array();
foreach($tmp as $type => $labels)
{
$count = 0;
foreach ($labels as $value) {
if($value['read']==0){ $count++; }else{ $count = 0;}
}
$output[] = array(
'sender' => $type,
'unread_count' => $count,
'items' => $labels
);
}
echo json_encode($output);