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

时间:2016-10-25 15:48:29

标签: php arrays sorting elasticsearch

我有一个像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
  ]
]

如您所见,此数组按字母顺序排列。我想要做的是通过“key”字段来命令这个数组,但是通过认为它是一个整数值来命令它。预期结果是:

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

]

3 个答案:

答案 0 :(得分:2)

尝试== Compilation error on file lib/protocols/units_convert.ex == ** (UndefinedFunctionError) function ConvertMacro.defimpl_convert_for/1 is undefined or private. Did you mean one of: * defimpl_convert_for/1 ConvertMacro.defimpl_convert_for([UdioDb.Block]) (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

natsort - 使用"自然顺序排序数组"算法

答案 1 :(得分:1)

您可以使用自然比较和usort函数:

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

答案 2 :(得分:0)

是的,您可以使用usort ...以下是一个如何完成的示例:

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