计算多维数组中的不同值

时间:2021-06-15 01:53:25

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:

原始$ result数组如下所示:

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?

我已经在for循环中经历了in_array语句的各种迭代,但仍然无法使其工作。有人可以帮忙吗?

1 个解决方案

#1


4  

I wouldn't use in_array() personally here.

我不会在这里亲自使用in_array()。

This just loops through creating the array as it goes.

这只是循环创建数组。

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

它似乎无需先将索引设置为0即可工作。

$newArray = array();

foreach($result as $key => $group) {   
    foreach($group as $member) {
        $newArray[$key][$member]++;
    }    
}

#1


4  

I wouldn't use in_array() personally here.

我不会在这里亲自使用in_array()。

This just loops through creating the array as it goes.

这只是循环创建数组。

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

它似乎无需先将索引设置为0即可工作。

$newArray = array();

foreach($result as $key => $group) {   
    foreach($group as $member) {
        $newArray[$key][$member]++;
    }    
}