user1403546
user1403546

Reputation: 1749

PHP - sort nth-level subarray

Let's suppose I've a nested PHP array $aaa where the entry $aaa[$bbb][$ccc] is like

array(0 => array('x' => 3, 'y' => 2), 1 => array('x' => 2, 'y' => 1), 2 => array('x' => 4, 'y' => 1))

and let's say I want to order just this array by x value in order to get the array

array(0 => array('x' => 2, 'y' => 1), 1 => array('x' => 3, 'y' => 2), 2 => array('x' => 4, 'y' => 1))

and not modify all the other subarrays. How can I do it? I'm not able to do it with usort and a custom function.

Upvotes: 1

Views: 123

Answers (4)

Don't Panic
Don't Panic

Reputation: 41820

usort is an easy way to do this (not clear why yours wouldn't have worked), and if you're using PHP 7, It's a great opportunity to use one of the new features, <=>, the combined comparison operator, (AKA the spaceship).

usort($your_array, function($a, $b) {
    return $a['x'] <=> $b['x'];
});

The spaceship operator is used for comparing two expressions. It returns -1, 0 or 1 when $a is respectively less than, equal to, or greater than $b.

(If you're not using PHP 7, then of course you can still use usort with a different comparison function, or other approaches, as the other answers here have shown.)

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

Assuming that you have defined $bbb and $ccc as the keys; extract the x keys from the array and sort that, sorting the original array:

array_multisort(array_column($aaa[$bbb][$ccc], 'x'), $aaa[$bbb][$ccc]);

Upvotes: 0

Razib Al Mamun
Razib Al Mamun

Reputation: 2711

You can use with usort like bellow :

<?php  
function compare_func($key) {
    return function ($a, $b) use ($key) {
        return strnatcmp($a[$key], $b[$key]);
    };
}

$name = array(0 => array('x' => 3, 'y' => 2), 1 => array('x' => 2, 'y' => 1), 2 => array('x' => 4, 'y' => 1));
usort($name, compare_func('x'));
print_r($name);
?>

Output : Array ( [0] => Array ( [x] => 2 [y] => 1 ) [1] => Array ( [x] => 3 [y] => 2 ) [2] => Array ( [x] => 4 [y] => 1 ) )

For more details http://php.net/manual/en/function.usort.php

Upvotes: 0

BVengerov
BVengerov

Reputation: 3007

Yet it can be done with usort

$arr = array(
    0 => array('x' => 3, 'y' => 2),
    1 => array('x' => 2, 'y' => 1),
    2 => array('x' => 4, 'y' => 1)
);

function cmp($a, $b)
{
    if ($a['x'] == $b['x']) {
        return 0;
    }
    return ($a['x'] < $b['x']) ? -1 : 1;
}

usort($arr, "cmp");

var_dump($arr);

Result

array(3) {
  [0]=>
  array(2) {
    ["x"]=>
    int(2)
    ["y"]=>
    int(1)
  }
  [1]=>
  array(2) {
    ["x"]=>
    int(3)
    ["y"]=>
    int(2)
  }
  [2]=>
  array(2) {
    ["x"]=>
    int(4)
    ["y"]=>
    int(1)
  }
}

Upvotes: 3

Related Questions