3

I have updated my question so please check it.

I have one array like below:

$array = [
  0 => [
    "term" => "DECATHLON",
    "count" => 7,
  ],
  1 => [
    "term" => "babywalz",
    "count" => 6,
  ],
  2 => [
    "term" => "Douglas",
    "count" => 3,
  ],
  3 => [
     "term" => "NETFLIX",
     "count" => 2,
  ],
  4 => [
    "term" => "zalando",
    "count" => 2,
  ],
  5 => [
    "term" => "Ernsting's family",
    "count" => 1,
  ],
  6 => [
    "term" => "Spotify",
    "count" => 1,
  ],
  7 => [
    "term" => "eventim",
    "count" => 1,
  ]
];

I want to sort array like this:

$array = [
        1 => [
            "term" => "babywalz",
            "count" => 6,
        ],
        0 => [
            "term" => "DECATHLON",
            "count" => 7,
        ],
        2 => [
            "term" => "Douglas",
            "count" => 3,
        ],
        5 => [
            "term" => "Ernsting's family",
            "count" => 1,
        ],
        7 => [
            "term" => "eventim",
            "count" => 1,
        ],
        3 => [
            "term" => "NETFLIX",
            "count" => 2,
        ],
        6 => [
            "term" => "Spotify",
            "count" => 1,
        ],
    ];

Any suggestions will be helpful. I have used asort(), but it doesn't work as I want. Also I have tried with natcasesort().

Jigar Pancholi
  • 1,009
  • 1
  • 7
  • 23

6 Answers6

4

Thanks for your valuable help. I have solved my issue as below:

usort($value, function($x, $y) { 
    return strcasecmp($x['term'], $y['term']); 
});
Jigar Pancholi
  • 1,009
  • 1
  • 7
  • 23
1

This will sort your array non-case sensitively:

natcasesort($array);

So:

natcasesort($array);
echo "Natural order sorting (case-insensitive):\n";
print_r($array);
mayersdesign
  • 4,231
  • 4
  • 27
  • 44
0

You have to use natcasesort, find more details here

$array = [    'D', 'a', 'Z', 'f'];    
natcasesort ($array);     
print_r($array);

Output

Array ( [1] => a [0] => D [3] => f [2] => Z )
0

You should use usort with custom user function

usort($array, function($a, $b){ 
    return strnatcmp (strtolower($a["term"]), strtolower($b["term"]));
});
Max Chernopolsky
  • 619
  • 6
  • 17
-1

Use function sort() like this: sort($array).

See the documentation: array sorting

Timur Gilauri
  • 632
  • 5
  • 12
-1
natcasesort($array);

Natural order sorting (case-insensitive)