Search code examples
phparrayssorting

How to sort an array by its keys


I grouped an array using the following script

$grouped_array = array();       
foreach($ungrouped_array as $item) {
    //group them by id
    $grouped_array[$item['id']][] = $item;
}

Now this grouped array looks like this

array(3) {
  [1]=>
  array(2) {
    [0]=>
    array(1) {
      ["id"]=>
      string(1) "1"
    }
    [1]=>
    array(1) {
      ["id"]=>
      string(1) "1"
    }
  }

  [6]=>
  array(1) {
    [0]=>
    array(1) {
      ["id"]=>
      string(1) "6"
    }
  }

  [2]=>
  array(4) {
    [0]=>
    array(1) {
      ["id"]=>
      string(1) "2"
    }
    [1]=>
    array(2) {
      ["id"]=>
      string(1) "2"
      ["sub"]=>
      string(1) "1"
    }
    [2]=>
    array(2) {
      ["id"]=>
      string(1) "2"
      ["sub"]=>
      string(1) "2"
    }
    [3]=>
    array(1) {
      ["id"]=>
      string(1) "2"
    }
  }
}

I have deleted the most part of the array to make it shorter but there is no [0] field in this grouped array All array fields are given the name of [id]'s value. I have no problem with that, I just have to short it again by [ID]

any suggestion will be great.


Solution

  • This should work to get 1, 2, 6:

    <?php
    $grouped_array = array();       
    foreach($ungrouped_array as $item) {
        $grouped_array[$item['id']][] = $item;
    }
    
    // sort by key.
    ksort( $grouped_array, SORT_NUMERIC );
    
    print_r( $grouped_array );