开发者

How to sort associative array using sub-field of contained associative arrays in PHP?

How can I sort an associative array by one of its values?

For example:

$arr = array(
    'ted' => array( 'age' => 27 ),
    'bo开发者_运维百科b' => array( 'age' => 18 ),
    'jay' => array( 'age' => 24 )
);

$arr = ???

foreach ($arr as $person)
    echo $person['age'], ', ';

So that the output is:

18, 24, 27

This is an oversimplified example just to demonstrate my question.

I still require that $arr is an associative array.


The uasort() function allows you to specify a callback function, which will be responsible of doing the comparison between two elements -- so, should do just well, if you implement the proper callback function.

Here, you'd have to implement a callback function that will receive two arrays -- and compmare the age item :

function callback($a, $b) {
  if ($a['age'] > $b['age']) {
    return 1;
  } else if ($a['age'] < $b['age']) {
    return -1;
  }
  return 0;
}


Using that function in the following portion of code :

$arr = array(
    'ted' => array( 'age' => 27 ),
    'bob' => array( 'age' => 18 ),
    'jay' => array( 'age' => 24 )
);

uasort($arr, 'callback');
var_dump($arr);

You would get you this resulting array :

array
  'bob' => 
    array
      'age' => int 18
  'jay' => 
    array
      'age' => int 24
  'ted' => 
    array
      'age' => int 27


This is a classical example where PHP 5.3 anonymous functions come in handy:

uasort($arr, function($a, $b) {
    return $a['age'] - $b['age'];
});

The $a['age'] - $b['age'] is a small trick. It works because the callback function is expected to return a value < 0 is $a is smaller than $b and a value > 0 if $a is bigger than $b.


Since you're sorting on a value inside a sub array, there's not a built-in function that will do 100% of the work. I would do a user-defined sort with:

http://www.php.net/manual/en/function.uasort.php

Here's an example comparison function that returns its comparison based on this value in the nested array

<?php
// Comparison function
function cmp($left, $right) {
    $age1 = $left['age'];
    $age2 = $right['age'];
    if ($age1 == $age2) {
        return 0;
    }
    return ($age1 < $age2) ? -1 : 1;
}

uasort($array, 'cmp');


http://www.php.net/manual/en/array.sorting.php

This particular case will involve using one of the sort methods that use a callback to sort


You're not just sorting an associative array, you're sorting an associative array of associative arrays ;)

A uasort call is what you're after

uasort($array, function ($a, $b) {
    if ($a['age'] === $b['age']) {
        return 0;
    }
    return $a['age'] > $a['age'] ? 1 : -1;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜