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
  ]

]
1

3 Answers 3

2

Try natsort

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

Sign up to request clarification or add additional context in comments.

1 Comment

Correct! Thank you so much
1

You can use natural comparison along with usort function:

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

Comments

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;
});

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.