简体   繁体   English

如何使用array_multisort()对PHP中的对象数组进行排序?

[英]How do I use array_multisort() to sort an array of objects in PHP?

I'm struggling to get array_multisort() working. 我正在努力让array_multisort()工作。 I'm sorting some data retrieved from JSON that is an array of five objects, each with data for blog posts in this format: 我正在对从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" ]    },

...etc ...等等

I get the file in PHP, decode the JSON into an associative array and then create an array of human readable dates which I have working. 我用PHP获取文件,将JSON解码为关联数组,然后创建一个人类可读日期数组,我已经工作了。 I have an array of five objects and need to sort the array by said dates. 我有一个包含五个对象的数组,需要按照所述日期对数组进行排序。 I then try to use array_multisort and cannot seem to find a syntax that work. 然后我尝试使用array_multisort,似乎无法找到有效的语法。 Any help would be appreciated and I'm sure it's something small I'm over-looking. 任何帮助将不胜感激,我相信这是一个小我看起来过度的东西。 No matter how hard I google, I just can't seem to get the search string right. 无论我多么努力,我似乎​​都无法获得正确的搜索字符串。 Help please? 请帮助?

  <?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);

For Reference See Below Code. 供参考见下面的代码。

$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;
}

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

EDIT: After reading comments, checking out other threads that were valuable like this one: Sort multidimensional array by multiple keys and ignoring the PHP docs here: http://php.net/manual/en/function.array-multisort.php 编辑:阅读评论后,检查其他有价值的线程如下: 按多个键排序多维数组并忽略PHP文档: http//php.net/manual/en/function.array-multisort.php

I got my code working by using the array of indices by which array_multisort () sorts is the FIRST array provided. 我通过使用索引数组来使我的代码工作,array_multisort()排序是提供的FIRST数组。 Again, the first argument passed to array_multisort() IS SORTED BY rather than the array you want sorted. 同样,第一个参数传递给array_multisort()IS SORTED BY而不是您想要排序的数组。 This is contrary to the PHP docs but seems to work. 这与PHP文档相反,但似乎有效。 If you find a misinterpretation or mistake in my code for why it is working, please let me know. 如果您发现我的代码中有误解或错误,请告知我们。 Until then, the fix for my code ended up being this: 在那之前,我的代码的修复最终是这样的:

array_multisort($date_sort, SORT_DESC, $json_content); array_multisort($ date_sort,SORT_DESC,$ json_content);

It seems to sort $date_sort by descending order placing newest dates first and then sort the second array of objects by how the the first was sorted. 它似乎按降序排序$ date_sort,先放置最新的日期,然后按第一个排序的方式排序第二个对象数组。 I got the idea thinking of how programs like Excel would sort a table based on a single column. 我想到了像Excel这样的程序如何根据单个列对表进行排序。

Thank you for taking the time to give me feedback and ask questions. 感谢您抽出宝贵时间给我反馈并提出问题。 All of it was helpful in eventually figuring out the wording of the docs seemed opposite (as the array that is sorted-by is itself sorted too (of course), but that is not the intention of calling the function and it is the other arrays that are themselves sorted relative to the first array). 所有这些都有助于最终弄清楚文档的措辞似乎相反(因为排序的数组本身也是排序的(当然),但这不是调用函数的意图,而是其他数组它们本身是相对于第一个数组排序的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM