简体   繁体   English

按儿童对usort排序多维数组

[英]Sort multidimensional array with usort by children

I'm working within the CakePHP framework, and have the following multidimensional array that I will need to sort by values. 我在CakePHP框架内工作,并具有以下多维数组,需要按值对它们进行排序。 I'm using usort , but cannot figure out how to sort by the children of [ForumPost] . 我正在使用usort ,但无法弄清楚如何按[ForumPost]的子级进行排序。

Here's the array: 这是数组:

Array
( 
    [0] => Array
        (
            [ForumPost] => Array
                (
                    [id] => 174
                    [forum_id] => 81
                    [user_id] => 39
                    [title] => A test post
    [1] => Array
        (
            [ForumPost] => Array
                (
                    [id] => 64
                    [forum_id] => 208
                    [user_id] => 36
                    [title] => B test post
... etc

My function and call are: 我的函数和调用是:

usort($array, array("ForumSearchesController", "cmp"));

function cmp($a, $b) {
    return $a['ForumPost']['title'] - $b['ForumPost']['title'];
}

You cannot simply subtract titles (strings) from each other and expect a meaningful result. 您不能简单地相互减去标题(字符串)并期望得到有意义的结果。 The equivalent for strings is calling the function strcmp : 与字符串等效的是调用函数strcmp

function cmp($a, $b) {
    return strcmp($a['ForumPost']['title'], $b['ForumPost']['title']);
}

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

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