Nested scopes in ionic

Hi,

I am facing problem with nested scopes in ionic sqlite.

my coding is,

$scope.sections = [];
$cordovaSQLite.execute(db, “select section_id, section_name from section”,[]).then(function(sections) {
if (sections.rows.length > 0) {
for (var i=0; i<sections.rows.length; i++) {
$scope.sections.push({
sectionId : sections.rows.item(i).section_id,
sectionName : sections.rows.item(i).section_name,
students : []
});
$cordovaSQLite.execute(db, “select student_id, student_name from student where section_id = ?”,[sections.rows.item(i).section_id]).then(function(students) {
if (students.rows.length > 0) {
for (var j=0; j<students.rows.length; j++) {
$scope.sections.students.push({
studentId : students.rows.item(j).student_id,
studentName : students.rows.item(j).student_name
});
}
} else {
console.log(“No results found 2”);
}
},
function(error) {
console.log("Error on loading: " + error.message);
});
}
} else {
console.log(“No results found 2”);
}
},
function(error) {
console.log("Error on loading: " + error.message);
});

My json output should be in the following format

sections = [
{
sectionId = ‘1’,
sectionName : ‘section1’,
students : [
{
studentId : 1,
studentName : ‘student1’
},
{
studentId : 2,
studentName : ‘student2’
},
{
studentId : 3,
studentName : ‘student3’
}
]
},
{
sectionId = ‘2’,
sectionName : ‘section2’,
students : [
{
studentId : 4,
studentName : ‘student4’
},
{
studentId : 5,
studentName : ‘student5’
},
{
studentId : 6,
studentName : ‘student6’
}
]
},
{
sectionId = ‘3’,
sectionName : ‘section3’,
students : [
{
studentId : 7,
studentName : ‘student7’
},
{
studentId : 8,
studentName : ‘student8’
},
{
studentId : 9,
studentName : ‘student9’
}
]
}
]

Please help me to resolve this issue.
Thanks in advance.