0

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
  ]

]
T. Cem Yılmaz
  • 500
  • 9
  • 30
  • Try to use the usort function. Please, look there http://stackoverflow.com/questions/2699086/sort-multi-dimensional-array-by-value – Mistery Oct 25 '16 at 15:56

3 Answers3

2

Try natsort

natsort — Sort an array using a "natural order" algorithm.

Manh Nguyen
  • 930
  • 5
  • 12
1

You can use natural comparison along with usort function:

usort($buckets, function($a, $b) {
    return strnatcmp($a->key, $b->key);
});
Rudolf Ratusiński
  • 1,087
  • 1
  • 8
  • 8
0

Yes you can use usort...here is an example of how it can be done:

usort($a['buckets'], function($a, $b) {
  $a_int = (integer) $a['key'];
  $b_int = (integer) $b['key'];
  if ($a_int === $b_int) return 0;
  return ($a_int > $b_int) ? 1 : -1;
});
WEBjuju
  • 5,797
  • 4
  • 27
  • 36
  • Hello! Thank you for your answer!. As @Mistery pointed out the usort function I began to search it and found natural sorting in php. I am gonna post my answer – T. Cem Yılmaz Oct 25 '16 at 16:02