gpt4 book ai didi

php - 多维数组按值排序,同时将其转换为整数

转载 作者:行者123 更新时间:2023-12-03 00:41:04 24 4
gpt4 key购买 nike

我有一个像这样的数组,它来自ElasticSearch。由于我无法从Elasticsearch订购此汇总。 Elasticsearch仅支持按计数顺序或按字母顺序排序。我决定在PHP方面进行此操作。

"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
]
]

如您所见,该数组是按字母顺序排列的。我想做的是通过“键”字段对该数组进行排序,但是通过认为它是整数值来对其进行排序。预期结果是:
"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
]

]

最佳答案

您可以将自然比较与usort函数一起使用:

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

关于php - 多维数组按值排序,同时将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40244359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com