排序时保留JSON数组 [英] Preserve JSON arrays while sorting

查看:48
本文介绍了排序时保留JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个来自外部网站的JSON数组。我对两个数组进行排序和合并,对它们进行解码,然后按ID从最高到最低排序。

I have two JSON arrays coming from an external website. I sort and merge the two arrays, decode them and then sort them from highest to lowest by ID.

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

Currently, when the option 'alphabetical' is clicked, ?sort=alphabetical is added onto the end of the URL and when the page has finished reloading, the JSON arrays are once again decoded and merged.

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

This is not my desired outcome: I do not want the JSON arrays to be decoded and merged again when the option is clicked - I simply want the already decoded and merged JSON arrays to be sorted alphabetically.

数组:

$homepage = array();  

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

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






排序:


Sorting:

$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, function ($a, $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传递给它。

You could use JavaScript for doing the sorting on click, and use PHP only for passing the JSON to it.

在提供了要显示列表的HTML结构后,我将此答案更新为使用 div 元素作为记录, p 元素用于字段。

After you provided the HTML structure you want to display the list in, I updated this answer to use div elements for the records and p elements for the fields.

我们可以用两个按钮替换选择列表,以选择排序顺序。

We could replace the select list, for selecting the sort order, by two buttons.

这里是PHP代码:

<?php

$homepage = array();  

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

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

$data = array();
foreach ($homepage as $homepage2) {
    $tmp=json_decode($homepage2, false);
    $data = array_merge($data,$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, function (a, 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,您可以在此处测试:

For the sample data this will result in the following JavaScript/HTML, which you can test here:

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, function (a, b) {
    return a.ID - b.ID;
});

var populateByName = populate.bind(null, function (a, 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和名称的排序顺序相同。

Note that I gave the three items different ID values than in your question, since otherwise the sort order would be the same for both ID and Name.

有很好的JavaScript库可以提供更多的功能来表示数据集。以下是使用jQuery和 DataTables 的示例:

There are nice JavaScript libraries which give much more features to represent data sets. Here is an example using jQuery with DataTables:

var collection = [{"Name":"Charlie","ID":"13"},{"Name":"Emma","ID":"9"},{"Name":"Bob","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解决方案更小(不包括所包含的库)。但这有分类上下,过滤,分页,漂亮的风格,......

The actual code is even smaller (not counting the included library) than a pure JavaScript solution would be with a basic table. But this has sorting up and down, filtering, pagination, nice styles, ...

这篇关于排序时保留JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆