我是一名设计代码点火器项目的设计师,我坚持这个问题!
我有这个数组
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
)
示例并不完全匹配,但您可以看到我想要实现的目标。感谢每个人!!!
答案 0 :(得分:1)
您可以使用array_keys()
获取第一个数组的键,explode()
来剪切逗号,然后,如果explode提供了多个元素,请检查该元素是否存在,以及增加1,或创建新的。
这是第一个版本,甚至未经过测试:
$array1 = array(); // The array you show
$array2 = array(); // The resulting array
$keys = array_keys($array1);
foreach($keys as $key)
{
$chunks = explode(',', $key);
foreach($chunks as $chunk)
{
if(isset($array2[$chunk]))
$array[$chunk] += $array1[$key];
else
$array[$chunk] = $array1[$key];
}
}
答案 1 :(得分: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
)
答案 2 :(得分:1)
尝试这样的事情:
$result = array();
foreach($data as $str_keys => $value) {
$keys = explode(',', $str_keys);
foreach($keys as $key) {
if(isset($result[$key])) {
$result[$key] += $value;
} else {
$result[$key] = $value;
}
}
}
print_r($result);