简体   繁体   中英

php sort by key multidimentional array

Supposed I have an array of

array(8) {
  [0] =>
  array(1) {
    'Peter' =>
    int(4)
  }
  [1] =>
  array(1) {
    'Piper' =>
    int(4)
  }
  [2] =>
  array(1) {
    'picked' =>
    int(4)
  }
  [3] =>
  array(1) {
    'peck' =>
    int(4)
  }
  [4] =>
  array(1) {
    'pickled' =>
    int(4)
  }

How can I sort this multidimentional array by key example (Peter). I tried using

ksort($arr);

but it just return a boolean

The output that I want

array(8) {
      [0] =>
      array(1) {
        'peck' =>
        int(4)
      }
      [1] =>
      array(1) {
        'Peter' =>
        int(4)
      }
      [2] =>
      array(1) {
        'picked' =>
        int(4)
      }
      [3] =>
      array(1) {
        'pickled' =>
        int(4)
      }
      [4] =>
      array(1) {
        'piper' =>
        int(4)
    }

the array should be sorted by key and in ascending order.

Sort with usort like this, check the demo

usort($array,function($a,$b){
    return strcmp(strtolower(key($a)),strtolower(key($b)));
});

The ksort() method does an in-place sort. So while it only returns a boolean (as you correctly state), it mutates the values inside $arr to be in the sorted order. Note that based on your expected output, it looks like you want to do a case insensitive search. For that, you need to use the SORT_FLAG_CASE sort flag. So, instead of calling ksort($arr) , you instead want to use ksort($arr, SORT_FLAG_CASE) . You can see how ksort() uses sort flags, in the sort() method's documentation . Hope that helps!

You can do something like this,

$temp = array_map(function($a){
    return key($a); // fetching all the keys
}, $arr);
natcasesort($temp); // sorting values case insensitive
$result = [];
// logic of sorting by other array
foreach($temp as $v){
    foreach($arr as $v1){
        if($v == key($v1)){
            $result[] = $v1;
            break;
        }        
    }
}

Demo

Output

Array
(
    [0] => Array
        (
            [peck] => 4
        )

    [1] => Array
        (
            [Peter] => 4
        )

    [2] => Array
        (
            [picked] => 4
        )

    [3] => Array
        (
            [pickled] => 4
        )

    [4] => Array
        (
            [Piper] => 4
        )

)

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