T. Cem Yılmaz T. Cem Yılmaz - 1 month ago 20
PHP Question

Multidimensional array sorting by value while casting it as integer

I have an array like this which comes from ElasticSearch. Since I cannot order this aggregations from elasticsearch. Elasticsearch has only support order by count or order by alphabetical. I decided to do this in PHP's side.

"buckets" => array:8 [
0 => array:2 [
"key" => "1 Ft."
"doc_count" => 6
]
1 => array:2 [
"key" => "10 Ft."
"doc_count" => 10
]
2 => array:2 [
"key" => "15 Ft."
"doc_count" => 10
]
3 => array:2 [
"key" => "20 Ft."
"doc_count" => 10
]
4 => array:2 [
"key" => "25 Ft."
"doc_count" => 10
]
5 => array:2 [
"key" => "3 Ft."
"doc_count" => 10
]
6 => array:2 [
"key" => "5 Ft."
"doc_count" => 10
]
7 => array:2 [
"key" => "7 Ft."
"doc_count" => 10
]
]


As you can see this array is alphabetical ordered. What I wanted to do is order this array by "key" field but order it by thinking it's an integer value. Expected result is :

"buckets" => array:8 [
0 => array:2 [
"key" => "1 Ft."
"doc_count" => 6
]
1 => array:2 [
"key" => "3 Ft."
"doc_count" => 10
]
2 => array:2 [
"key" => "5 Ft."
"doc_count" => 10
]
3 => array:2 [
"key" => "7 Ft."
"doc_count" => 10
]
4 => array:2 [
"key" => "10 Ft."
"doc_count" => 10
]
5 => array:2 [
"key" => "15 Ft."
"doc_count" => 10
]
6 => array:2 [
"key" => "20 Ft."
"doc_count" => 10
]
7 => array:2 [
"key" => "25 Ft."
"doc_count" => 10
]

]

Answer

You can use natural comparison along with usort function:

usort($buckets, function($a, $b) {
    return strnatcmp($a->key, $b->key);
});