3

I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.

The original $result array looks like this:

Array
(
    [sku] => Array
        (
            [0] => 344
            [1] => 344
            [2] => 164
        )

    [cpk] => Array
        (
            [0] => d456
            [1] => d456
        )
)

I'm trying to take this and create a new array:

$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;

I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?

1
  • I removed the "potential solution" tags that you added to this question to prevent the XY Problem. Commented Feb 11, 2012 at 21:21

1 Answer 1

5

I wouldn't use in_array() personally here.

This just loops through creating the array as it goes.

It seems to work without needing to first set the index as 0.

$newArray = array();

foreach($result as $key => $group) {   
    foreach($group as $member) {
        $newArray[$key][$member]++;
    }    
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Ralph Don't know. I guess if I do arithmetic (++) on it, it is case to an integer of 0.

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.