dongwen9947 2017-06-18 04:32
浏览 52
已采纳

按字母顺序排序多维数组

[0] => Array (
    [term] => punk
    [term_html] => <a href=""> punk </a>
    )
[1] => Array (
    [term] => conflict
    [term_html] => <a href=""> conflict </a>
    )
[2] => Array (
    [term] => Crass
    [term_html] => <a href=""> Crass </a>
    )
[3] => Array (
    [term] => bct 2
    [term_html] => <a href="">
    )

How can I sort this array alphabetically based on 'term' of the array inside array?

i tried this:

function sortByOrder($a, $b) {
    return $search_terms_html[term];
}

uasort($search_terms_html, 'sortByOrder');

but it doesn't work :(

  • 写回答

2条回答 默认 最新

  • dongyuduan1890 2017-06-18 04:40
    关注

    The comparison callback function passed to uasort() is expected to return a value < 0, 0, or > 0, describing the relationship between its arguments. In your example, the callback is simply returning the the unchanging value $search_terms_html[term]; you are not using the arguments representing the array elements (and passed as parameters to the callback function, sortByOrder()). Assuming that the 'term' elements are strings, try defining the callback as:

    function sortByOrder($a, $b) {
       return strcmp($a['term'],$b['term']);
    }
    

    strcmp() returns values of a sting comparison consistent with the callback's expectations.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?