我编写了从数据库中选择数据的代码,通过2个参数(match_day和competition_id)对数组进行分组并生成JSON
foreach ($result as $res) {
$day = date('d', $res["match_start_time"]);
$json["response"][] = array(
"competition_id" => $res["competition_id"],
"match_start_time" => $res["match_start_time"],
"match_day" => $day
);
}
$arr = array();
$arr["items"] = array();
foreach($json["response"] as $key => $item)
{
if(!isset($arr['items'][$item['match_day']][$item['competition_id']])){
$arr['items'][$item['match_day']][$item['competition_id']] = array();
$arr['items'][$item['match_day']][$item['competition_id']]['league'] = $item['competition_id'];
$arr['items'][$item['match_day']][$item['competition_id']]['day'] = $item['match_day'];
}
$arr['items'][$item['match_day']][$item['competition_id']]['matches'][] = $item;
}
$arr['items'] = array_values($arr['items']);
echo json_encode($arr);
此代码为我提供了以下JSON
{
"items": [
{
"cuefa": {
"league": "cuefa",
"day": "01",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285873500"
}
]
}
},
{
"cuefa": {
"league": "cuefa",
"day": "30",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285866000"
}
]
}
}
]
}
我无法删除items数组中的competition_id。如何更改代码以获取以下JSON?
{
"items": [
{
"block": [
{
"league": "cuefa",
"day": "01",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285873500"
}
]
}
]
},
{
"block": [
{
"league": "cuefa",
"day": "30",
"matches": [
{
"competition_id": "cuefa",
"match_start_time": "1285866000"
}
]
}
]
}
]
}
答案 0 :(得分:1)
在json_encode
:
foreach ($arr['items'] as &$item) {
$item = array('block' => array_values($item));
}