gpt4 book ai didi

php - 对 PHP 数组进行排序、分组和计数

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

关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。












想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。

8年前关闭。



Improve this question




我是一名从事代码点火器项目的设计师,我被这个问题困住了!

我有这个数组

Array
(
[Science] => 7
[War] => 5
[Mystery] => 2
[Preview Only] => 2
[Conspiracy,News ] => 2
[Drugs,Educational,Lifestyle,Society] => 1
[Educational,Nature,Science,Space] => 1
[Religion,Society] => 1
[Music] => 1
[Movies,Music] => 1
[Lifestyle] => 1
[Countries,Educational,History,War] => 1
[Educational,Society] => 1
[Science,Space,Technology] => 1
[Economics,Educational,Lifestyle,Society] => 1
[Society] => 1
[Biology,Conference,Educational] => 1
[Human Rights,Society] => 1
[Art and Artists,Biographies,Music] => 1
[Biology,Educational,Science] => 1
[Activist,Biology,Science,Society] => 1
[Countries,Drugs,War] => 1
[Drugs,War] => 1
[Technology,War] => 1
[History,War] => 1
[Biology,Educational,Environment,Nature,Science] => 1
[Science,Technology] => 1
[Educational,Science,Space] => 1
[Educational,History,Human Rights,War] => 1
[Environment] => 1
[Biographies] => 1
[Evolution,Science] => 1
[Art and Artists] => 1
)

正如您在那里看到的那样,它已经按数字排序。我想要实现的是从数组中删除任何重复的类别,并为每个类别添加一个 +1,结果如下:
Array
(
[Science] => 14
[War] => 11
[Mystery] => 2
[Preview Only] => 2
[Conspiracy] => 2
[Society] => 4
[Nature] => 1
[space] => 1
[Religion] => 1
[Music] => 2
[Movies] => 1
[Lifestyle] => 1
[Countries] => 1
[Educational] => 12
[Space] => 1
[Lifestyle] => 1
[Society] => 3
[Biology] => 3
[Economics] => 1
[Science] => 1
[Activist] => 1
[Countries] => 1
[Drugs] => 3
[Technology] => 2
[History] => 1
[Biology] => 1
[Technology] => 1
[Space] => 1
[History] => 1
[Human Rights] =>
[Environment] => 1
[Biographies] => 2
[Evolution] => 1
[Art and Artists] => 1
)

这些示例并不完全匹配,但您可以看到我想要实现的目标。谢谢大家!!!

最佳答案

function do_the_magic( $array ){
$result = array();
foreach ($array as $k=>$value){
foreach (explode(',',$k) as $category){
$result[$category] += $value;
}
}
return $result;
}

例子:
$a['ala,ma']=1;
$a['ala']=2;
print_r(do_the_magic($a));

结果
Array ( 
[ala] => 3
[ma] => 1
)

关于php - 对 PHP 数组进行排序、分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18171544/

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