【问题标题】:How do I use array_multisort() to sort an array of objects in PHP?如何使用 array_multisort() 对 PHP 中的对象数组进行排序?
【发布时间】:2017-05-16 05:11:19
【问题描述】:

我正在努力让 array_multisort() 工作。我正在对从 JSON 检索到的一些数据进行排序,这是一个由五个对象组成的数组,每个对象都包含这种格式的博客文章数据:

  "1":{"title": "It's a fixer-upper of a planet but we could make it work",
  "post_date": "1454889600",
  "author": "Elon Musk",
  "content": "<p>We choose to go to the moon in this decade and do the other things...</p>",
  "category": [ "mars", "space travel" ]    },    

  "2":{"title": "Failure is not an option",
  "post_date": "1456099200",
  "author": "Gene Kranz",
  "content": "<p>Dinosaurs are extinct today because ...</p>",
  "category": [ "mis-quoted", "apollo 13" ]    },

...等

我在 PHP 中获取文件,将 JSON 解码为关联数组,然后创建我正在工作的人类可读日期数组。我有一个由五个对象组成的数组,需要按所述日期对数组进行排序。然后我尝试使用 array_multisort 并且似乎找不到有效的语法。任何帮助将不胜感激,我相信这是我忽略的小事。无论我多么努力地用谷歌搜索,我似乎都无法正确找到搜索字符串。请帮忙?

  <?php    //This part I'm confident is working.
    $json = file_get_contents("./data/posts.json");
    $json_content = json_decode($json, true);
    $date_sort = array ();

    //Sorting the Array - this part seems to work
    foreach ($json_content as $postObj) {
      $post_date_human = date ('Y-m-d', $postObj['post_date']);
      array_push($date_sort, $post_date_human);
    }
    print_r ($date_sort); //Seems to be working fine, now to try to sort one array of objects by the position of dates in the second array

    // Wai u no werk!?
    array_multisort($json_content, $date_sort = SORT_ASC);
    print_r ($json_content);

【问题讨论】:

  • 对不起.. 你真正想做什么?
  • 我想使用 array_multisort() 方法按发布日期排序博客文章,从最新到最旧。 :)
  • 看你下面的帖子好像你自己解决了...对吧?
  • 是的 - 我只是无法选择它作为 24 小时的答案。非常感谢您回来查看:)。

标签: php arrays sorting object array-multisort


【解决方案1】:

编辑:阅读 cmets 后,查看其他有价值的线程,例如:Sort multidimensional array by multiple keys 并忽略此处的 PHP 文档:http://php.net/manual/en/function.array-multisort.php

我的代码通过使用 array_multisort () 排序的索引数组是提供的第一个数组来工作。同样,传递给 array_multisort() 的第一个参数是 SORTED BY 而不是您要排序的数组。这与 PHP 文档相反,但似乎有效。如果您在我的代码中发现其工作原因的误解或错误,请告诉我。在那之前,我的代码的修复最终是这样的:

array_multisort($date_sort, SORT_DESC, $json_content);

似乎 $date_sort 按降序排序,将最新日期放在首位,然后按第一个对象的排序方式对第二个对象数组进行排序。我想到了 Excel 之类的程序如何根据单列对表格进行排序。

感谢您抽出宝贵时间向我提供反馈和提问。所有这些都有助于最终弄清楚文档的措辞似乎相反(因为排序的数组本身也是排序的(当然),但这不是调用函数的意图,而是其他数组它们本身是相对于第一个数组排序的)。

【讨论】:

    【解决方案2】:

    供参考,请参见下面的代码。

    $json_content = msort($json_content, "post_date");
    
    And heres the function itself:
    
    /**
     * Sort a 2 dimensional array based on 1 or more indexes.
     * 
     * msort() can be used to sort a rowset like array on one or more
     * headers (keys in the 2th array).
     * 
     * @param array        $array      The array to sort.
     * @param string|array $key        The index(es) to sort the array on.
     * @param int          $sort_flags The optional parameter to modify the sorting 
     *                                 behavior. This parameter does not work when 
     *                                 supplying an array in the $key parameter. 
     * 
     * @return array The sorted array.
     */
    function msort($array, $key, $sort_flags = SORT_REGULAR) {
        if (is_array($array) && count($array) > 0) {
            if (!empty($key)) {
                $mapping = array();
                foreach ($array as $k => $v) {
                    $sort_key = '';
                    if (!is_array($key)) {
                        $sort_key = $v[$key];
                    } else {
                        // @TODO This should be fixed, now it will be sorted as string
                        foreach ($key as $key_key) {
                            $sort_key .= $v[$key_key];
                        }
                        $sort_flags = SORT_STRING;
                    }
                    $mapping[$k] = $sort_key;
                }
                asort($mapping, $sort_flags);
                $sorted = array();
                foreach ($mapping as $k => $v) {
                    $sorted[] = $array[$k];
                }
                return $sorted;
            }
        }
        return $array;
    }
    

    欲了解更多信息,请访问:https://blog.jachim.be/2009/09/php-msort-multidimensional-array-sort/comment-page-1/

    【讨论】:

    • 为了让它与我的对象数组一起工作而进行的一个小改动是将$sort_key .= $v[$key_key]; 行更改为$sort_key .= $v-&gt;$key_key;。谢谢你!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 2015-11-11
    • 1970-01-01
    • 2019-11-02
    • 2010-12-04
    • 2015-01-24
    • 2011-01-18
    相关资源
    最近更新 更多