使用jQuery JSON数据对数组进行排序

时间:2011-12-07 20:53:05

标签: jquery json

我试图弄清楚如何对php脚本提供的数组进行排序。 php脚本将html文件放在一个目录中,然后将它们传递给jQuery,jQuery然后获取它们并在页面上显示它们。这就是我所拥有的:

<script>
 $(document).ready(function(){
   $.getJSON('helper.php', function(data) {
     var items = [];
     $.each(data, function(key, val) {
       $.get("articles/" + val, function(html){
             $("#postdata").append(html);
           }, 'html');
     });
   });
 });
</script>

如何对它们进行排序(或反向)排序?文件名的格式为{S} -post-slug.html,其中{S}是纪元后的秒数。我希望能够先用最新的文件显示它们。

3 个答案:

答案 0 :(得分:1)

这可能就是你所期待的。 http://phpjs.org/functions/ksort:460

几乎是php ksort的工作原理。

答案 1 :(得分:0)

这并不是特别容易,因为你有N个异步$.get()操作并行进行,每个操作都在未知时间结束。我能想到的唯一选择是:

  1. 保存数组中的所有数据并在插入任何内容之前对数组进行排序,然后按排序顺序插入它们。这样做的缺点是,在检索完所有数据之前,页面中不会出现任何数据。
  2. 当文章到达时,按正确的顺序插入每个文章。这可能是最好的用户体验,但写的代码最多。
  3. 插入所有文章,然后在完成最后一篇文章时,在DOM中对它们进行排序。这会在内容到达时显示内容,但随后将其全部移动。这可能是最不可取的。
  4. 这是一种在每篇文章到达时按顺序插入它们(它们可以以任何顺序到达)的方式,我认为这是最好的用户体验。文章将在到达时按顺序出现:

     $(document).ready(function(){
       $.getJSON('helper.php', function(data) {
         $.each(data, function(key, val) {
            $.get("articles/" + val, function(html){
    
                // parse the article time out of the filename
                var time = 0;
                var matches = val.match(/\d+/);
                if (matches) {
                    time = parseInt(matches, 10);
                }
    
                // create new article and tag it with an identifying class
                // and the filename time
                var o = $(html);
                o.data("ftime", time);
                o.addClass("timedArticle");
    
                // now find where to insert this article (newest articles first)
                // by finding the first article whose time is less than the 
                // time of the article to insert
                var target;
                $("#postdata").children(".timedArticle").each(function() {
                    if ($(this).data("ftime") < time) {
                        target = this;
                        return(false);
                    }
                });
                if (target) {
                    o.insertBefore(target);
                } else {
                    $("#postdata").append(o);
                }
            }, 'html');
         });
       });
     });
    

答案 2 :(得分:0)

以下是一种在JavaScript中执行此操作的方法,但如果您可以对数据服务器端进行排序,那么您的用户会非常感激:

 $(function(){
   var jqXHR = [],//setup an array to store references to the `$.get()` jqXHR objects
       arr   = [],//setup an array to store the URLs and sort them numerically
       obj   = {};//setup an object o link URLs to HTML
   $.getJSON('helper.php', function(data) {
     $.each(data, function(key, val) {

       //add each `$.get()` request to our queue
       jqXHR.push($.get("articles/" + val, function(html){

             //add the URL to our array
             arr.push(val);

             //add the HTML to our object referenced by the URL
             obj[val] = html;
           }, 'html'));
     });

     //run the sort/append code after all the AJAX calls have been finished
     $.when(jqXHR).then(function () {

         //sort the array numerically descending
         arr.sort(function(a,b){

             //only sort by the numeric values in the URLs which should be everything before the first `-` character (hyphen)
             a = a.split('-')[0];
             b = b.split('-')[0];
             return b - a
         });

         //iterate through our array of sorted URLs and concoct them into a HTML string
         var len = arr.length,
             out = '';
         for (var i=0; i<len; i++) {
             out += obj[arr[i]];
         }

         //append our HTML string to the DOM
         $("#postdata").append(out);
     });
   });
 });