0
[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 :(

3
  • Possible duplicate of Sort multidimensional array alphabetically Commented Jun 18, 2017 at 4:36
  • uksort(); ....... Commented Jun 18, 2017 at 4:36
  • just tested with uksort() ... same result Commented Jun 18, 2017 at 4:39

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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
  • Bcde
  • Cdef
  • Defg

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.