我有一个与此问题类似的问题:PHP Sort Array By SubArray Value,但有一点不同,因为我想查找/搜索许多子数组值中的最高值,然后对“主”数组进行排序。 下面是我拥有的数组结构,其中的分组包含多个子项,每个子项都有一个得分。
Array
(
[grouping1] => Array
(
[0] => Array
(
[_score] => 8.2
[_source] => Array
(
[name] => Subitem 1111,
[ID => 999
)
)
)
[grouping2] => Array
(
[0] => Array
(
[_score] => 8.546042
[_source] => Array
(
[name] => Subitem2222,
[ID] => 987654
)
)
)
[grouping3] => Array
(
[0] => Array
(
[_score] => 10.163501
[_source] => Array
(
[name] => Subitem3333
[ID] => 12345
)
)
[1] => Array
(
[_score] => 8.55
[_source] => Array
(
[name] => Subitem4444,
[ID] => 67890
)
)
[2] => Array
(
[_score] => 9.55
[_source] => Array
(
[name] => Subitem5555
[ID] => 65421
)
)
)
)
我想
预期输出是具有此顺序的包含数组
答案 0 :(得分:0)
好的,这就是您需要做的-在每个max
中找到grouping
分,并存储一个查询[grouping -> score]
,然后对该查询数组进行排序以保留键并构建新的数组:>
$lookup = [];
foreach ($source_array as $key => $grouping) {
$max = 0;
foreach ($grouping as $item) {
if ($max < $item['_score']) {
$max = $item['_score'];
}
}
$lookup[$key] = $max;
}
// sort `$lookup` preserving keys
arsort($lookup);
$sorted_array = [];
foreach ($lookup as $key => $max) {
$sorted_array[$key] = $source_array[$key];
}