将SQL查询返回的记录拆分为一个数组

Splitting SQL query returned records into an array

本文关键字:数组 一个 拆分 查询 SQL 返回 记录      更新时间:2023-09-26

嘿,我想把我返回的查询记录分割成一个"分页"类型的东西,因此我想显示前51条记录,然后将其余的添加到一个数组中,以便在用户想要移动到另一个页面时稍后获取。

我可以在页面上显示前51个结果,但是我在找到将其余记录除以51的方法时遇到了麻烦。

我的代码:

var arrayHTML       = [];
for(var key in data){
    if(data.hasOwnProperty(key)) {
        if (totalX >= 51) {
            //Start putting the results into an array. 51 results per array
        }else if (x > 1) {
            x = 0;
            _userName = data[key].fname + ' ' + data[key].lname;
            populateCards(_userName, 
                          data[key].email, 
                          data[key].img, 
                          data[key].school, 
                          data[key].userID, 
                          true,
                          data[key].encoded);
        } else {
            _userName = data[key].fname + ' ' + data[key].lname;
            populateCards(_userName, 
                          data[key].email, 
                          data[key].img, 
                          data[key].school, 
                          data[key].userID, 
                          false, 
                          data[key].encoded);
            x++;
        }
        totalRowCnt = data[key].totalRows;
        _tmpMath = Math.round(totalRowCnt / totalNum);
        total++;
        totalX++;
        console.log('totalX: ' + totalX)
    }
}

在它命中51之后,它进入if (totalX>= 51) {,这就是我试图弄清楚如何将其余部分分割成51每个数组插槽。

上面的代码循环,直到它到达每个第三条记录,然后放置一个
之后,所以它有一行3条记录,然后它只是继续这样做,直到它达到记录51。 17行,每行3条记录。true告诉函数将
放在末尾,而false告诉函数不要将
on yet.

任何帮助将是伟大的!

JavaScript代码:

将这个函数添加到你的代码中:

// this is a simple pager function that return part of the array you want
//  so you can easily loop over it
// @param page you want
// @param how many values you want
// @return the sliced array with the parts you want
//     (this will return an empty array if your page is out of bound
//       e.g. when you array only contains less than 51 and you tell it you want page 2)
array_pager = function ( array, page, show ) {
   var start = (page -1) * show; // this sets the offset
   return array.slice( start, start + show);
}

你可以像这样使用这个函数:

// assuming the array's name is data
var this_page = array_pager( data, 1, 51); // get this_page 1, with 51 values
// then you can safely loop over it
for(var key in this_page) {
  _userName = this_page[key].fname + ' ' + this_page[key].lname;
  populateCards(_userName, 
                this_page[key].email, 
                this_page[key].img, 
                this_page[key].school, 
                this_page[key].userID, 
                false, 
                this_page[key].encoded);
}
// for page 2: array_pager( data, 2, 51) ... 
// 10 per page: array_pager( data, 1, 10) ... I think you get it now