0

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

1 Answer 1

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

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanx, but that's not exactly what I was looking for. I think my problem starts from a badly designed mysql table. It keeps 2 values inside a cell separated by comma and when I query the table I don't know how to put each value to a different key in the array, so they end up in the same key. Thanx anyway.
Split the values when you fetch the row, then assign them to the array manually, rather than as part of the fetch command.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.