如何将多个键值拆分为数组中的单独键?

时间:2011-04-14 16:21:04

标签: php arrays

我有这个数组

Array ( 
    [0] => Array ( 
        [0] => Array ( [value] => Cooking, [occurence] => 1 ) 
        [1] => Array ( [value] => Music, [occurence] => 1 ) 
        [2] => Array ( [value] => Football,Cooking, [occurence] => 1 ) 
        [3] => Array ( [value] => Travel, [occurence] => 1 ) 
        [4] => Array ( [value] => Cooking,Reading, [occurence] => 2 ) 
        [5] => Array ( [value] => Football,Travel, [occurence] => 1 ) 
        [6] => Array ( [value] => Football, [occurence] => 1 ) 
        [7] => Array ( [value] => Music,Cooking, [occurence] => 1 ) 
        [8] => Array ( [value] => Reading,Travel, [occurence] => 1 )
    )
) 

[2],[4],[5],[7]和[8]为键[值]有2个值。 我想要做的是将这些键的2个值分成不同的键。

新值不应该转到新的数组,但它们会被添加到类似的现有数组中。

例如,如果我打破[2](足球,烹饪),结果将是[6](足球)的出现将增加1并且[0](烹饪)的[出现]将也增加1。

谢谢! 晏

1 个答案:

答案 0 :(得分:1)

$newdata = array()
foreach($array as $data) { // $array being the inner array with the 9 elements
   $keys = explode(',', $data['value']);
   foreach ($keys as $subkey) {
       $newdata[$subkey]++;
   }
}

会给你类似的东西

$newdata = array(
    'Cooking' => 4,
    'Football' => 3
    etc...
);

不确定您希望自己的结构看起来如何,但至少这会为您做清单。