我怎么能算,减少在数组中值的发生? [英] How can I count and reduce the occurence of a value in an array?

查看:218
本文介绍了我怎么能算,减少在数组中值的发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,看起来像这样:

 阵列

    [0] =>排列
        (
            [名] =>测试
            [...] => ...
        )    [1] =>排列
        (
            [名] =>红酒
            [...] => ...        )
    [2] =>排列
        (
            [名] =>红酒
            [...] => ...
        ))

现在,我要实现的是这样的:

 阵列

    [0] =>排列
        (
            [名] =>测试
            [事件] => 1
            [...] => ...
        )    [1] =>排列
        (
            [名] =>红酒
            [occurence] => 2
            [...] => ...
        ))

总之,我想基于独特的名称键删除重复的项目,我想补充一个计数器发生来告诉我发生的频率每个项目的结果。该项目具有更多的按键,这应该是preserved(保持中第一次出现的值是罚款)。


解决方案

  $结果= [];
的foreach($数组作为$项目){
    如果(!使用isset($结果[$项目['名'])){
        $结果[$项目['名'] = $项目;
        $结果[$项目['名'] ['发生'] = 1;
    }其他{
        $结果[$项目['名'] ['发生'] ++;
    }
}

只需使用一个事实,即数组键是独一无二的,你必须在一个循环迭代重复数据删除的数据。

I have an array that looks like this:

Array
(
    [0] => Array
        (
            [name] => test
            [...]  => ...
        )

    [1] => Array
        (
            [name] => wine
            [...]  => ...

        )
    [2] => Array
        (
            [name] => wine
            [...]  => ...
        )

)

Now, what I want to achieve is something like this:

Array
(
    [0] => Array
        (
            [name] => test
            [occurrence] => 1
            [...]  => ...
        )

    [1] => Array
        (
            [name] => wine
            [occurence] => 2
            [...]  => ...
        )

)

In short, I want to deduplicate the items based on the unique name key, and I want to add a counter occurrence to the result which tells me how often each item occurred. The items have many more keys, which should be preserved (keeping the values of the first occurrence is fine).

解决方案

$result = [];
foreach ($array as $item) {
    if (!isset($result[$item['name']])) {
        $result[$item['name']] = $item;
        $result[$item['name']]['occurrence'] = 1;
    } else {
        $result[$item['name']]['occurrence']++;
    }
}

Simply use the fact that array keys are unique, and you'll have your data deduplicated in a single loop iteration.

这篇关于我怎么能算,减少在数组中值的发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆