javascript – 排序时保留JSON数组

前端之家收集整理的这篇文章主要介绍了javascript – 排序时保留JSON数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个 JSON数组来自外部网站.我排序并合并两个数组,对它们进行解码,然后按ID从最高到最低排序.

目前,当单击“按字母顺序”选项时,将sort = alphabetical添加到URL的末尾,当页面重新加载完成后,JSON数组将再次被解码并合并.

这不是我想要的结果:我不希望JSON数组在单击该选项时再次被解码和合并 – 我只是希望已经解码和合并的JSON数组按字母顺序排序.

阵列:

$homepage = array();  

$homepage[]= '{  
   "info":{  
      "collection":[  
         {  
            "Name":"Charlie","ID":"7"
         },{  
            "Name":"Emma","ID":"9"
         }
      ]
   }
}';  

$homepage[] = '{  
   "info":{  
      "collection":[  
         {  
            "Name":"Bob","ID":"5"
         }
      ]
   }
}';

排序:

$data = array();
foreach ($homepage as $homepage2) {
    $tmp=json_decode($homepage2,false);
    $data = array_merge($data,$tmp->info->collection);
}

if(!empty($_GET['sort']) && $_GET['sort'] == 'alphabetical') {
    usort($data,function ($a,$b) {
        return strcmp($a->Name,$b->Name);
    });
}else{
    usort($data,$b) {
        return $b->ID - $a->ID;
    });
}

echo'
<select onchange="location.href = this.value;">
    <option value="example.PHP?sort=alphabetical">Alphabetical</option>
</select>
';

foreach($data as $key) {
    echo'
    <a href="test.com">
    <p>'.$key->ID.'</p>
    <p>'.$key->Name.'</p>
    </a>
    ';
}

解决方法

您可以使用JavaScript进行点击排序,并仅使用PHP将JSON传递给它.

在您提供了要显示列表的HTML结构之后,我更新了此答案,以便为这些字段的记录和p元素使用div元素.

我们可以通过两个按钮替换选择列表,用于选择排序顺序.

以下是PHP代码

<?PHP

$homepage = array();  

$homepage[]= '{  
   "info":{  
      "collection":[  
         {  
            "Name":"Charlie","ID":"13"
         },"ID":"10"
         }
      ]
   }
}';

$data = array();
foreach ($homepage as $homepage2) {
    $tmp=json_decode($homepage2,$tmp->info->collection);
}

?>

<div id="container"></div>

<button id="sort1">Alphabetical</button>
<button id="sort2">High to Low</button>

<script>
    var collection = <?=json_encode($data)?>;

    function populate(compareFunc) {
        collection.sort(compareFunc);
        var container = document.getElementById('container');
        container.innerHTML = '';
        collection.forEach(function (key) {
            var div = document.createElement("div");
            div.className = "inventory";
            var span = document.createElement("span");
            span.textContent = key.ID;
            div.appendChild(span);
            span = document.createElement("span");
            span.textContent = key.Name;
            div.appendChild(span);
            container.appendChild(div);
        });
    }

    var populateById = populate.bind(null,function (a,b) {
        return a.ID - b.ID;
    });

    var populateByName = populate.bind(null,b) {
        return a.Name.localeCompare(b.Name);
    });

    document.getElementById("sort1").addEventListener('click',populateByName);
    document.getElementById("sort2").addEventListener('click',populateById);
    document.addEventListener('DOMContentLoaded',populateById);

</script>

对于示例数据,这将导致以下JavaScript / HTML,您可以在这里测试:

var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","ID":"10"}];

function populate(compareFunc) {
    collection.sort(compareFunc);
    var container = document.getElementById('container');
    container.innerHTML = '';
    collection.forEach(function (key) {
        var div = document.createElement("div");
        div.className = "inventory";
        var span = document.createElement("span");
        span.textContent = key.ID;
        div.appendChild(span);
        span = document.createElement("span");
        span.textContent = key.Name;
        div.appendChild(span);
        container.appendChild(div);
    });
}

var populateById = populate.bind(null,b) {
    return a.ID - b.ID;
});

var populateByName = populate.bind(null,b) {
    return a.Name.localeCompare(b.Name);
});

document.getElementById("sort1").addEventListener('click',populateByName);
document.getElementById("sort2").addEventListener('click',populateById);
document.addEventListener('DOMContentLoaded',populateById);
span { margin-left: 5px }
div.inventory { border-bottom: 1px solid gray }
<div id="container"></div>

<button id="sort1">Alphabetical</button>
<button id="sort2">High to Low</button>

请注意,我给出了三个不同于您的问题的ID值,因为否则排序顺序对于ID和Name都是相同的.

使用表:替代

有很好的JavaScript库可以提供更多的功能来表示数据集.这是一个使用jQuery与DataTables的例子:

var collection = [{"Name":"Charlie","ID":"5"}];

function populate() {
  var tbody = $('#collection>tbody');
  collection.forEach(function (key) {
    var row = $('<tr>');
    row.append($('<td>').text(key.ID));
    row.append($('<td>').text(key.Name));
    tbody.append(row);
  });
}

$(document).ready(function(){
  populate();
  $('#collection').DataTable();
});
<script src="http://code.jquery.com/jquery-1.12.3.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>

<table id="collection">
    <thead>
        <tr><th>ID</th><th>Name</th></tr>
    </thead>
    <tbody/>
</table>

实际的代码更小(不包括附带的库),而纯JavaScript解决方案将是一个基本的表.但是这样做有上下颠倒,过滤,分页,不错的风格…

原文链接:https://www.f2er.com/js/153979.html

猜你在找的JavaScript相关文章