2016-04-04 134 views
0

我目前正在嘗試使用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對象目前正在建設這樣如果restruc這將有助於我更願意這樣做。

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)); 
+1

「組」不能是一個對象數組嗎? – Ankh

+0

我已經添加了用於首先創建對象的PHP。 – Doug

+0

所以問題仍然存在,重要的'$鑰匙'?如果沒有,那麼你可以使組成一個數組而不是一個對象。 [例如](https://jsfiddle.net/1yz3urh7/) – Ankh

回答

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陣列中。

Example fiddle