3 回答
TA贡献2051条经验 获得超10个赞
尝试这个 :
let arr = [
{"1" : [{"start": "", "end": ""}]},
{"2" : [{"start": "", "end": ""}]},
{"3" : [{"start": "", "end": ""}]},
{"4" : [{"start": "", "end": ""}]},
{"5" : [{"start": "", "end": ""}]},
{"6" : [{"start": "", "end": ""}]},
{"7" : [{"start": "", "end": ""}]},
];
let obj = {};
arr.map((item,index) => {
obj[index + 1] = item[index + 1];
});
console.log(obj);
TA贡献1844条经验 获得超8个赞
感谢您的编辑建议。在对 JSON 格式进行了一些挖掘后,我发现我需要创建数组对象而不是数组:
//Getting all days data from DB given user ID
$aDays = Schedule::getDays($nIdUser);
//Object Array to Store Data
$oJson = (object)array();
//Iteration
foreach ($aDays as $aInfoDay) {
//Getting single day hour ranges given day ID
$aRangesHours = Schedule::getDayRanges("id_day = {$aInfoDay['id_day']} AND id_user = {$nIdUser}");
//Array to Store all Hour Ranges in a Day
$aParsedDay = array();
//Iterate Ranges
foreach ($aRangesHours as $aRangeHour) {
//Object Array to Store Single Hour Range
$oRange = (object)array();
$oRange->start = $aRangeHour['startHour'];
$oRange->end = $aRangeHour['endHour'];
//Pushing Range object to $aParsedDay Array, this is for keeping the [{"start":"","end":""},...}] format
array_push($aParsedDay,$oRange);
//Saving $aParsedDay in $oJson Object, the name of the index will be the current 'id_day'
$oJson->{$aRangeHour['id_day']} = $aParsedDay;
}
}
//result
echo json_encode($oJson);
获取所需的格式:
{
"1" : [{"start": "12:00:00", "end": "13:00:00"}],
"2" : [{"start": "09:00:00", "end": "10:00:00"},{"start": "10:00:00", "end": "12:00:00"}],
"3" : [{"start": "15:00:00", "end": "16:00:00"},{"start": "16:00:00", "end": "17:00:00"}]
}
TA贡献1806条经验 获得超8个赞
当你这样做时$aJson[] = $aParseDay;,你正在考虑$aJson一个$aParseDay对象数组。您需要做的是更改要分配的第二个 foreachstart和内部end的id_day键$aJson。
foreach ($aDays as $aInfoDay) {
$aRangesHours = Schedule::getDayRanges("id_day = {$aInfoDay['id_day']} AND id_user = {$nIdUser}");
$aParsedDay = [];
foreach ($aRangesHours as $aRangeHour) {
$aJson[$aRangeHour['id_day']][] = ['start' => $aRangeHour['startHour'],'end' => $aRangeHour['endHour']];
}
}
- 3 回答
- 0 关注
- 169 浏览
添加回答
举报