我目前正在尝试使用AngularJS扩展/推送/合并对象我的问题是,当我扩展它时,添加一个索引为0的对象,我不能再添加它们了相同的指数0
//Original Object
{ "groups": {
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"}
}
}
//After running function
{ "groups": {
"0": { "id": "1", "name": "object0"}, //This is the new object no more can then be added
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"}
}
}
//What I want
{ "groups": {
"1": { "id": "1", "name": "object1"},
"2": { "id": "2", "name": "object2"},
"3": { "id": "3", "name": "object3"},
"4": { "id": "4", "name": "object4"} // etc
}
}
我目前正在使用这个:
$scope.addGroup = function () {
angular.extend($scope.audit.groups,[
{
"name": "",
"questions": []
}
]);
}
jsfiddle = https://jsfiddle.net/U3pVM/23760/
目前正在构建PHP对象,如果重组这将有助于我更愿意这样做。
public function getAllQuestionGroupsByAuditIdArray($id) {
$questions = new Question();
foreach ($this->getAllQuestionGroupsByAuditId($id) AS $key => $group) {
$QuestionGroups[$key] = array(
"id" => $group['id'],
"name" => $group['name'],
"questions" => $questions->getQuestionsByGroupIdArray($group['id'])
);
}
return $QuestionGroups;
}
$this->response = array(
"name" => $auditData['name'],
"groups" => $questionGroups->getAllQuestionGroupsByAuditIdArray($id),
);
return print_r(json_encode($this->response));
答案 0 :(得分:1)
在PHP中,我们可以更新响应以返回非关联数组或类似的组:
$QuestionGroups = array();
foreach ($this->getAllQuestionGroupsByAuditId($id) AS $key => $group) {
$QuestionGroups[] = array(
"id" => $group['id'],
"name" => $group['name'],
"questions" => $questions->getQuestionsByGroupIdArray($group['id'])
);
}
转换为JSON时,这将返回groups
作为对象数组而不是对象对象。
然后,您只需使用.push()
将更多群组附加到groups
数组中。