0

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.

Beginner
  • 1,700
  • 4
  • 22
  • 42

3 Answers3

1

Sort with usort like this, check the demo

usort($array,function($a,$b){
    return strcmp(strtolower(key($a)),strtolower(key($b)));
});
LF00
  • 27,015
  • 29
  • 156
  • 295
0

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!

entpnerd
  • 10,049
  • 8
  • 47
  • 68
0

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
        )

)
Rahul
  • 18,271
  • 7
  • 41
  • 60