【问题标题】:Change order of JSON in PHP without key/value pair在没有键/值对的情况下更改 PHP 中 JSON 的顺序
【发布时间】:2015-12-10 09:10:53
【问题描述】:

我有一种情况,我需要按日期对 JSON 对象进行排序。我在网上搜索了解决方案,一切都指向 PHP 的 usort 函数的方向,但 all examples 有一个键/值对可以排序。

这是我加载提要的方式:

$ret = file_get_contents($url);
$res = json_encode($ret);

以下 JSON 的结果

{  
   "2015-12-14":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
  },
   "2015-12-15":{  
      "direction":"S",
      "snowfall":3.0,
      [..]
   },
   "2015-12-12":{  
      "direction":"SE",
      "snowfall":0.0,
      [..]
   },
   "2015-12-13":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   },
   "2015-12-10":{  
      "direction":"E",
      "snowfall":0.0,
      [..]
   },
   "2015-12-11":{  
      "direction":"S",
      "snowfall":0.0,
      [..]
   }
}

如您所见,数据未按日期正确排序,但日期值是关键,所以我如何按日期对对象进行排序(2015-12-10、2015-12-11、2015-12- 12、2015-12-13、2015-12-14、2015-12-15)?

【问题讨论】:

    标签: php json


    【解决方案1】:

    只需在编码之前对数据进行排序,例如ksort:

    $ret = file_get_contents($url);
    ksort($ret);
    $res = json_encode($ret);
    

    这样,$ret 似乎返回的数组将按键(日期)排序,然后按该排序顺序进行编码。

    【讨论】:

      【解决方案2】:
      $json = '{  
         "2015-12-14":{  
      
            "direction":"S",
      
            "snowfall":0.0
      
        },
      
         "2015-12-15":{  
      
            "direction":"S",
      
            "snowfall":3.0
      
         },
      
         "2015-12-12":{  
      
            "direction":"SE",
      
            "snowfall":0.0
      
         },
      
         "2015-12-13":{  
      
            "direction":"S",
      
            "snowfall":0.0
      
         },
      
         "2015-12-10":{  
      
            "direction":"E",
      
            "snowfall":0.0
      
         },
      
         "2015-12-11":{  
      
            "direction":"S",
      
            "snowfall":0.0
      
         }
      
      }';
      
      $array = get_object_vars(json_decode($json));
      
      ksort($array);
      
      echo json_encode((object)$array);
      

      【讨论】:

        【解决方案3】:

        您可以使用ksort,它可以按键对您的数组进行排序。

        您也可以使用排序标志,它们在here 中得到了很好的描述。

        【讨论】:

          猜你喜欢
          • 2021-05-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-09-17
          • 2012-09-21
          • 1970-01-01
          • 1970-01-01
          • 2016-10-15
          相关资源
          最近更新 更多