Search code examples
phparrayssortingnestedsub-array

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.


Solution

  • 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)
      }
    }