2

私はコード イグナイター プロジェクトに取り組んでいるデザイナーですが、この問題で立ち往生しています!

私はこの配列を持っています

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
)   

例は完全には一致しませんが、私が達成しようとしていることを見ることができます。みんな、ありがとう!!!

4

3 に答える 3

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);
于 2013-08-11T11:48:32.610 に答える
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 
)
于 2013-08-11T11:46:29.767 に答える