gpt4 book ai didi

php - 使用php过滤掉数组中的重复值

转载 作者:行者123 更新时间:2023-12-05 08:35:21 25 4
gpt4 key购买 nike

请帮助我使用 php.Consider 过滤掉数组中的重复值,

$arr1 = array('php','jsp','asp','php','asp')

这里我宁愿只打印

array('php'=>2,
'asp'=>2)

试过

print_r(array_count_values($arr1));

但是,它获取每个元素的计数。

最佳答案

好的,在评论和重读你的问题之后,我明白你的意思了。使用 array_count_values() 就差不多了:

$arr1 = array('php','jsp','asp','php','asp');
$counts = array_count_values($arr1);

您只需删除显示为仅出现一次的条目:

foreach ($counts as $key => $val) {
if ($val == 1) {
unset($counts[$key]);
}
}

编辑:不想循环?使用 array_filter() 代替:

// PHP 5.3+ only
$counts = array_filter($counts, function($x) { return $x > 1; });

// Older versions of PHP
$counts = array_filter($counts, create_function('$x', 'return $x > 1;'));

关于php - 使用php过滤掉数组中的重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3583558/

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