简体   繁体   中英

How do I sort this array

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM