简体   繁体   English

按字母顺序排序多维数组

[英]sorting multi dimensional array alphabetically

[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 :( 但这不起作用:(

The comparison callback function passed to uasort() is expected to return a value < 0, 0, or > 0, describing the relationship between its arguments. 传递给uasort()的比较回调函数应返回值<0、0或> 0,以描述其参数之间的关系。 In your example, the callback is simply returning the the unchanging value $search_terms_html[term] ; 在您的示例中,回调仅返回不变的值$search_terms_html[term] you are not using the arguments representing the array elements (and passed as parameters to the callback function, sortByOrder() ). 您没有使用表示数组元素的参数(并作为参数传递给回调函数sortByOrder() )。 Assuming that the 'term' elements are strings, try defining the callback as: 假设'term'元素是字符串,请尝试将回调定义为:

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

strcmp() returns values of a sting comparison consistent with the callback's expectations. strcmp()返回与回调的期望一致的字符串比较值。

Easiest way I find out to sort an entire multidimensional array by one element of it: 我发现用一个元素对整个多维数组排序的最简单方法:

<?php 
$multiArray = Array( 
    Array("id" => 1, "name" => "Defg"), 
    Array("id" => 2, "name" => "Abcd"), 
    Array("id" => 3, "name" => "Bcde"), 
    Array("id" => 4, "name" => "Cdef")); 
$tmp = Array(); 
foreach($multiArray as &$ma) 
    $tmp[] = &$ma["name"]; 
array_multisort($tmp, $multiArray); 
foreach($multiArray as &$ma) 
    echo $ma["name"]."<br/>"; 


?> 

Outputs 产出

  • Abcd A B C D
  • Bcde Bcde
  • Cdef Cdef
  • Defg 定义

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

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