【问题标题】:Is it possible to either map or sort an object of arrays in Javascript是否可以在Javascript中映射或排序数组对象
【发布时间】:2017-09-25 21:00:33
【问题描述】:

我从数据库中获取了一堆数据,并想在一个表中显示所有数据,但数据没有排序。有没有一种方法可以对数组对象进行排序或映射,以便我知道什么内容与什么内容相匹配,从而在每一行中显示正确的数据?

这是我获取数据的 ajax 调用:

        //get the content, display all pages or specified page num
        $.ajax({
            type: 'POST', 
            url: 'qry/getRawText.php',
            async: true,
            data: {FileId: fileId, PageNum: pageNum},
            success: function(response) {
                getRawTextResponse = JSON.parse(response);
                drawTextCodeContent();
           }
        });

这里是我用数据绘制表格的地方:

 function drawTextCodeContent() {
      fileText = "<table id='fileTextTableId'><tbody>";

        //loop through text files
        for(i=0;i<getRawTextResponse.length;i++) {
            //remove null from text
            if(getRawTextResponse["RowData"][i] == null) {
                getRawTextResponse["RowData"][i] == "";
            }
            //draw row
            fileText += "<tr class='rowToEdit " + getRawTextResponse["RowStatus"][i] + "'><td class='hidden'>"+ getRawTextResponse["PageNum"][i] +"</td><td class='rowNumTd'>"+ getRawTextResponse["RowNum"][i] +"</td><td class='rowContentTd'><pre>"+ getRawTextResponse["RowData"][i] +"</pre></td><td class='rowCheckboxTd'><label class='mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect mdl-data-table__select' for='row[" + getRawTextResponse["RowNum"][i] + "]'><input type='checkbox' id='row[" + getRawTextResponse["RowNum"][i] + "]' class='mdl-checkbox__input' /></label></td></tr>";                  
        }
        fileText += "</tbody></table>";
        //display table in div
        $("#textCodeDiv").html(fileText);
 }

这是数据实际外观的预览:

Object {
     PageNum: Array(66), 
     RowNum: Array(66), 
     RowStatus: Array(66),
     RowData: Array(66), 
     length: 66
 }

PageNum 和 RowNum 是不按顺序排列的数字数组。 行状态和行数据是不按顺序排列的字符串数组。

这是从数据库中获取数据的整个 PHP 文件:

$fileId = $_POST["FileId"];
$pageNum = $_POST["PageNum"];

// Populate the query string
$tsql = "Exec TxRrcT1.GetRawText @FileId = ?, @PageNum = ?";

// Attempt to connect to SQL Server
if ( strtoupper(substr(PHP_OS, 0, 3)) == "WIN" ){
    $conn = odbc_connect($connection_string, $user, $pass, SQL_CUR_USE_ODBC);
   if ($conn === false ){ die(); }
 }
else {
    $conn = odbc_connect($connection_string, $user, $pass);
    if ($conn === false ){ die(); } 
}

// Prepare the stored procedure
$sp = odbc_prepare($conn, $tsql);

$params = array(
   $fileId, //@FileId
   $pageNum //@PageNum
);

// Execute procedure
$qryResults = TransformToObjectWithArrays($sp, $params);

// Close the connection
if ($conn !== false){ odbc_close($conn); }

// Return the query results
if (isset($qryResults)){ echo json_encode($qryResults); }

这是我最初的 PHP 函数,用于获取数据并将其转换为数组对象。我怎样才能将其更改为仅返回数组数组中的数据?

// This function will prepare a tsql procedure and return the ODBC result
// identifier that can be used once the procedure is executed
function GetQryReturn($sp, $params){
    $qryReturn = odbc_execute($sp, CleanInputs($params));
    if ($qryReturn === false){ die(); }
    return $sp;
}

function CleanInputs($InputArray){
    return array_map(function($value){return $value === "" ? NULL : $value;}, $InputArray);
}

// This function takes a prepared stored procedure and any parameters and
// returns the query results as an objects with arrays
// example:
// {key1: [va1,val2], key2: [val1,val2]}
function TransformToObjectWithArrays($sp, $params){
    // Execute query
    $qryReturn = GetQryReturn($sp, $params);

    // Populate array with results
    $qryResults = array();
    if( odbc_num_rows($qryReturn) ){
        for($i=1; $i<=odbc_num_fields($qryReturn); $i++){
        $qryResults[odbc_field_name($qryReturn, $i)] = array();
    }
    $qryResults["length"] = 0;
    while( $row = odbc_fetch_array($qryReturn) ){
        foreach($row as $key => $value){
            array_push($qryResults[$key], $value);
        }
        $qryResults["length"] += 1;
    }
   }
   else{
        $qryResults["length"] = 0;
   }

   return $qryResults;
}

【问题讨论】:

  • 如果从db查询数据时对数据进行排序怎么办?就像使用参数来选择它必须对其进行排序的方式一样。我认为如果它是一堆数据并且没有分页,那么在 js 中排序可能会给您的应用在渲染之前带来糟糕的性能。
  • 你要传递什么给TransformToObjectWithArrays? IE。你的$sp$params?
  • @MajidFouladpour 我更新了问题
  • 所以...忽略您可能只是要求 SQL 对您的数据进行排序这一事实,让我确保我明白了:您收到来自 odbc_fetch_array 的响应,这是一个行数组,每一行都是一个关联的列数组,一个非常适合排序的结构;然后将其转置为一个关联的列数组,每一列都是一个值数组;然后你把它发送到客户端?为什么不直接将json_encode 的结果odbc_fetch_array 发送出去?它更容易显示为表格,更容易排序,更容易......一切。
  • 我不是数据库专家,我被告知要在客户端对其进行排序。如果我理解你,我相信我已经对 $qryResults 进行了 json_encoding .. 这是我给出的第一个 php 示例

标签: javascript php jquery arrays sorting


【解决方案1】:

一般来说,我建议在服务器端进行排序。否则,您始终可以使用DataTables。它支持客户端排序。有时使用起来可能很笨拙,但它确实为我节省了时间。

【讨论】:

  • 我应该使用PHP对数组的对象进行排序吗?我还是 PHP 新手,所以我不知道该怎么做
  • @Teton-Coder 如果您通过数据库查询SELECTing 数据,您最好的选择是使用ORDER BY 或等效的从数据库口获取数据.
  • 我使用 PHP 中的存储过程来调用数据。我将在哪里使用 Order By 功能?这是在存储过程之前、在其中还是在调用之后?
  • Teton,首先,我将更改您返回的数据的格式。您应该返回一个对象数组,而不是数组对象。其次,我不明白你为什么要包括 PageNum 和 RowNum。正确的实现不应该需要这些。是的,在服务器端(在 php 中)排序将是最直接的。事实上,通常 PHP 一次只会返回一页数据,因此有必要进行排序。 (或者是的,按照 Majid 的建议对您的查询进行排序 - 如果您可以使用,这是最好的)
  • 我使用 rowNum 和 pageNum 是因为用户正在编辑从网站上删除的错误数据。所以有些不干净,所以我们记录 page 和 rowNums 以便用户知道错误在哪里。
【解决方案2】:

你可以使用

arr.sort(compareFunction);

比较函数如下:

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

有关排序的更多信息,请点击此处https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort?v=control

对于映射使用类似这样的东西

var numbers = [1, 5, 10, 15];
var roots = numbers.map(function(x) {
   return x * 2;
});
这是完整映射选项的链接。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map?v=example

【讨论】:

  • 我怎样才能一次对整个数组对象进行排序呢?这样,所有数据都在正确的位置,或者至少一起映射在正确的位置。这样表格行将显示正确的数据
【解决方案3】:

我会将四个数​​组的对象转换为一个对象数组,每个对象都有对应于不同数组的四个字段。那就是:

[
    {
        PageNum: 0,
        RowNum: 0,
        RowStatus: 'status',
        RowData: 'data'
    }
]

然后您可以轻松地对整个数组进行排序

已编辑:

要对数组进行排序,您可以使用sort 方法:

var arr = [...]
arr.sort(function(a, b) {
    // a and b are two element of your array (e.g. arr[i] and arr[j])
    if(a.RowNum === b.RowNum) return 0;
    if(a.RowNum < b.RowNum) return -1;
    if(a.RowNum > b.RowNum) return 1;
})

【讨论】:

  • 如何将对象更改为数组?
  • @Teton-Coder 将对象更改为对象数组试试 data.PageNum.map((x,i) =&gt; ({ pagerow:x, rownum: data.RowNum[i], rowdata: data.RowData[i] })) ,希望你明白
  • @maioman 好的,我能够将它放入一个数组数组中,但我现在很难尝试按 rownum 排序......它会不会像 data.RowNum.sort( );
  • @lostInTheTetons 我在更新的回复中包含了排序代码
【解决方案4】:

如果有人想知道或供将来参考,这就是我想出的。我将它包含在我的 ajax 成功函数中。

getRawTextResponse = JSON.parse(response);                  
//getNewRawText and map data
gNRT = getRawTextResponse.PageNum.map((x,i) => ({
        index: i,
        PageNum: x, 
        RowNum: getRawTextResponse.RowNum[i], 
        RowData: getRawTextResponse.RowData[i],
        RowStatus: getRawTextResponse.RowStatus[i]
}));
//sort newly mapped array   
gNRT.sort(function(a,b) {return a.RowNum - b.RowNum});

【讨论】:

    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多