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

风格不统一 提交于 2019-12-06 10:01:18

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');
GordonM

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;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!