1

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.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
user1403546
  • 1,680
  • 4
  • 22
  • 43

4 Answers4

3

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)
  }
}
BVengerov
  • 2,947
  • 1
  • 18
  • 32
1

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.)

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

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

Razib Al Mamun
  • 2,663
  • 1
  • 16
  • 24
0

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]);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87