Yannis
Yannis

Reputation: 922

How to split multiple values of keys into separate keys in an Array?

I have this Array

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 )
    )
) 

The [2], [4], [5], [7] and [8] have 2 values for the key [value]. What I want to do is to split the 2 values of these keys in different keys.

The new values should not go to new Arrays, but they will be added to the similar existing Arrays.

For example, if I break the [2] (Football,Cooking) the result will be that the occurence of [6] (Football) will be incremented by 1 and the [occurence] of [0] (Cooking) will be incremented by 1 also.

Thank you ! Yann

Upvotes: 0

Views: 1385

Answers (1)

Marc B
Marc B

Reputation: 360702

$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]++;
   }
}

which would give you something like

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

Not sure how you want your structure to look afterwards, but at least this'll do the inventory for you.

Upvotes: 1

Related Questions