0

I need to sort my array by value in subarray. I have to do it in two options - desc sort and asc sort (so I need to define this param in function).

Here is my array:

array(5) {
  [0]=>
  array(2) {
    ["client_type"]=>
    string(5) "buyer"
    ["id"]=>
    string(3) "196"
  }
  [1]=>
  array(2) {
    ["client_type"]=>
    string(16) "seller"
    ["id"]=>
    string(3) "206"
  }
  [2]=>
  array(2) {
    ["client_type"]=>
    string(16) "buyer"
    ["id"]=>
    string(3) "206"
  }
  [3]=>
  array(2) {
    ["client_type"]=>
    string(16) "seller"
    ["id"]=>
    string(3) "206"
  }
  [4]=>
  array(2) {
    ["client_type"]=>
    string(16) "buyer_and_seller"
    ["id"]=>
    string(3) "206"
  }
}

I want sort this array by client_type array key (asc and desc). How I can do it? I checked this answer: PHP Sort Array By SubArray Value but it not solve my problem.

Thanks.

Pavel K
  • 235
  • 3
  • 15

3 Answers3

2

The answer you link to tells you exactly what you need to do, doesn't it? The only thing I would add is that you might appreciate the strnatcmp function for comparing strings rather than numbers. So you'd have:

function cmp_by_clientType($a, $b) {
  return strnatcmp($a["client_type"], $b["client_type"]);
}

usort($array, "cmp_by_clientType");

When you say the answer you link to doesn't work, what is the problem you're experiencing?

EDIT

For asc and desc the simplest would be to have two sort functions, so for DESC you'd have the same function but you swap $a and $b:

function cmp_by_clientType_DESC($a, $b) {
  return strnatcmp($b["client_type"], $a["client_type"]);
}

If you find this inelegant, you could maybe pass a boolean to the compare function, but that's more tricky. You can read more here:

Pass extra parameters to usort callback

Michael Beeson
  • 2,840
  • 2
  • 17
  • 25
2

On the example you are trying, they are using a number to compare and sort.

client_type is a string and you can use strcmp to compare strings.

For ASC:

$arr = //Your array
usort($arr, function($a, $b){
    return strcmp( $a['client_type'], $b['client_type'] );
});

For DESC:

$arr = //Your array
usort($arr, function($a, $b){
    return strcmp( $b['client_type'], $a['client_type'] );
});
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

You have to use the usort() php function. A link to the documentation is here : http://php.net/manual/en/function.usort.php Basically ,it works like this : You create a method delineating the logic whereby you want to sort your array, and then call that method as a callback in the usort() method.

Like this : keep in mind you can sum your data using array_sum() , or array_max() :

function sortArray($a, $b) {
    $suma = array_sum($a['score']); // or array_max
    $sumb = array_sum($b['score']); // or array_max

    if ($suma == $sumb) { 
       return 0; 
    }
    return ($suma < $sumb) ? 1 : -1 ;
  // or just : return $suma <=> $sumb ; // As of PHP 7


usort($array, 'sortArray');

Hope this helps you.

Christian