PHP:按子数组的出现次数对多维数组进行排序
Posted
技术标签:
【中文标题】PHP:按子数组的出现次数对多维数组进行排序【英文标题】:PHP: sorting a multidimensional array by number of occurrences of the sub arrays 【发布时间】:2022-01-12 02:36:39 【问题描述】:我想按子数组的出现次数对多维数组进行排序。
这是我的多维数组(它可以包含任何子数组,包含任何随机排序的值,这仅用于测试目的):
$items = array (
array ("00008", "Metal", "Melvins", "Working With God", "Sub Pop", "SP 009"),
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00021", "Techno", "Laurent Garnier", "Water Planet", "F Communications", "SDB00015"),
array ("00056", "LP", "Communards", "Communards", "RCA", "E 342-F"),
array ("00056", "LP", "Communards", "Communards", "RCA", "E 342-F"));
这样排序后的多维数组就变成了:
$items = array (
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00019", "LP", "Ray Parker", "The Other Woman", "EMI", "EMI02"),
array ("00056", "LP", "Communards", "Communards", "RCA", "E 342-F"),
array ("00056", "LP", "Communards", "Communards", "RCA", "E 342-F"),
array ("00008", "Metal", "Melvins", "Working With God", "Sub Pop", "SP 009"),
array ("00021", "Techno", "Laurent Garnier", "Water Planet", "F Communications", "SDB00015"));
目的是先出现3次的子数组,再出现2次的子数组。一次出现的所有子数组都可以随机出现。
可以使用单线完成吗?
例如:排序唯一性可以这样完成:
$uniques = array_intersect_key ($items, array_unique (array_map ("serialize", $items)));
非常感谢您帮助我!
【问题讨论】:
当您说“子数组的数量”时,您的意思是子数组中的第一项,就像一个ID,对吧?所以00019
是第一个,因为有三个子数组具有类似 ID 的东西。
【参考方案1】:
这似乎是您正在寻找的。至于单线,不确定。
// Grab the first column of each sub array, and then create an array
// mapping that ID to the number of times it was found in the main array
$counts = array_count_values(array_column($items, 0));
// Sort in reverse by value so that the greater quantity is first
arsort($counts);
// Custom sort where we look up the first column in our `$count` array
// and perform a spaceship comparison, going $b to $a so that the
// greater counts come first again.
usort(
$items,
static fn($a, $b) => $counts[$b[0]] <=> $counts[$a[0]]
);
在这里演示:https://3v4l.org/Lm7L9
我应该说,我不一定要提倡这个代码,它感觉很神秘,但它似乎工作。评论多于代码的事实对我来说是一种代码味道。
编辑
要将其转换为 php 7.0,您只需将 usort
中的箭头函数替换为传统的匿名函数即可:
usort(
$items,
static function ($a, $b) use ($counts)
return $counts[$b[0]] <=> $counts[$a[0]];
);
【讨论】:
非常感谢您的回答。这确实是我一直在寻找的。不幸的是,我坚持使用 php 7.0.33,所以我得到了解析错误。尽管如此,这个答案对我来说具有很大的教育价值。我自己永远也找不到。 @DasCrova,我已经为 PHP 7.0 更新了这个 谢谢!现在它工作正常。以上是关于PHP:按子数组的出现次数对多维数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章