【问题标题】:How Sort a multidimensional (json) array with PHP如何使用 PHP 对多维 (json) 数组进行排序
【发布时间】:2011-10-04 02:27:04
【问题描述】:

有人可以帮我吗...我已经阅读了以前的 PHP '排序'问题...并尝试遵循逻辑...但是大脑衰退盛行;-!

我有一个 json 对象(来自 facebook),我正在尝试使用以下代码使用其中一个值('created_time')对其进行排序:

$json = file_get_contents($url,0,null,null);
$result = json_decode($json, true);
array_multisort($note['created_time'], SORT_ASC, $result);   /* what's wrong with this line?? */

下图示例json数据:

{
   "data": [
      {
         "id": "123",
         "from": {
            "name": "Example",
            "category": "Musician/band",
            "id": "123"
         },
         "subject": "Subject 1",
         "message": "Example message text 1",
         "created_time": "2011-07-12T20:18:17+0000",
      },
      {
         "id": "123",
         "from": {
            "name": "Example",
            "category": "Musician/band",
            "id": "123"
         },
         "subject": "Subject 2",
         "message": "Example message text 2",
         "created_time": "2011-07-12T20:21:01+0000",
      },
...

感谢您的帮助。

【问题讨论】:

    标签: php json sorting


    【解决方案1】:

    您的 PHP sn-p 引用了一个 $note 对象,但我只看到了 $json 和 $result 变量...

    假设我们有可用的数据数组,您可以将 usort 与自定义函数一起使用。如果您使用的是 PHP 5.3+,这可能是一个匿名函数

    function sort_by_creation($a, $b) 
    {
      return (strtotime($a['created_time']) < strtotime($b['created_time']) ? -1 : 1;
    }
    usort($data, 'sort_by_creation');
    

    【讨论】:

    • 哎呀 - 对“$note”的引用完全是虚假/错误的 - 它来自我在尝试调试正在发生的事情时播放/尝试各种事情。
    【解决方案2】:

    我不确定这是否可行。 $note 是从哪里来的?如果您尝试按特定成员对数组进行排序,那么 usort 呢? http://php.net/manual/en/function.usort.php

    类似:

    function sortByCreatedTime($a, $b){
      if ($strtotime($a['data']['created_time']) == strtotime($b['data']['created_time'])) {
        return 0;
      };
      return ($strtotime($a['data']['created_time']) < strtotime($b['data']['created_time'])) ? -1 : 1;
    };
    usort($result, sortByCreatedTime);
    for($i = 0; $i < count($results['data']); $i++){
      //should output in descending order.  if not just change 
      //the < to a > in the sort function above
      echo 'time is => ' . $results['data']['created_time'] . '<br>';
    };
    

    【讨论】:

    • 感谢您的帮助 @Jake 和 @thescientist,但我无法让您的任何建议对我有用...您可以再试一次吗,既然我已经承认了'$note' 完全是虚假的。回顾一下-我的数组称为$result,其中的数据称为“数据”-在其中我需要排序的字段称为“created_time”再次感谢。
    • 嘿,忘了考虑内部的“数据”数组。看看上面的编辑是否有帮助。不确定您需要以哪种方式排序,ASC 与 DESC,但正如 cmets 中所述,它只是 gt/lt 符号的开关。
    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2013-09-01
    • 2014-02-25
    • 2016-09-27
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多