簡體   English   中英

SUM的JavaScript訂購JSON

[英]JavaScript order JSON by SUM

因此,我們有了一個JSON字符串,如下所示:

[{"id":"1499","tradingname":"Golden Shutter Photography","listed":"2012-01-26 19:26:24","pictureurl":"","business_id":"1499","storeid":"1","phone":"6143737477","street":"122 Avebery Drive","suburb":"Berwick ","state":"1","postcode":"3806","discription":"","long":"","lat":"","offer":"500|50","tstamp":"2012-01-26 19:26:24","offers":"500|50"}]

我們需要的是一種JavaScript方法來對結果進行排序/混排,以便他們接受要約並對其進行排序,從而顯示出最后的差異最大,而最先的差異較小。

例如,假設JSON中的優惠如下

100|10

100|20

100|9

它將按順序排列

100|20

100|10

100|9

現在的問題是,某些報價的報價多於1個報價,因此如下所示

100|20,100|9,100|10

在這種情況下,我們也想將100 | 9移到最后

100|20,100|10,100|9

這應該給您一個想法。 但是在調用json_encode之前使用multisort在php中對數組進行排序會更有效。

 var arr = [
      {"id":"1498","tradingname":"Golden Shutter Photography1","listed":"2012-01-26 19:26:24","pictureurl":"","business_id":"1499","storeid":"1","phone":"6143737477","street":"122 Avebery Drive","suburb":"Berwick ","state":"1","postcode":"3806","discription":"","long":"","lat":"","offer":"200|60","tstamp":"2012-01-26 19:26:24","offers":"200|40"},
      {"id":"1499","tradingname":"Golden Shutter Photography2","listed":"2012-01-26 19:26:24","pictureurl":"","business_id":"1499","storeid":"1","phone":"6143737477","street":"122 Avebery Drive","suburb":"Berwick ","state":"1","postcode":"3806","discription":"","long":"","lat":"","offer":"400|50","tstamp":"2012-01-26 19:26:24","offers":"200|50"},
      {"id":"1500","tradingname":"Golden Shutter Photography3","listed":"2012-01-26 19:26:24","pictureurl":"","business_id":"1499","storeid":"1","phone":"6143737477","street":"122 Avebery Drive","suburb":"Berwick ","state":"1","postcode":"3806","discription":"","long":"","lat":"","offer":"200|50","tstamp":"2012-01-26 19:26:24","offers":"400|50"}
    ];


    function sortbyoffer(a,b) {
      var aa = a.offer.split("|");
      var bb = b.offer.split("|");
      if(aa[0] == bb[0]) {
        return aa[1] - bb[1];
      } else {
        return aa[0] - bb[0]; 
      }
    }

    arr.sort(sortbyoffer);

    for(var n=0;n<arr.length;n++){
      document.write(arr[n].id + ' ' + arr[n].tradingname +  ' ' + arr[n].offer + '<br>');
    }

輸出將是:

1500 Golden Shutter Photography3 200|50
1498 Golden Shutter Photography1 200|60
1499 Golden Shutter Photography2 400|50

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM