获取关联数组中值的差

时间:2019-02-05 22:22:40

标签: php arrays

我有这个数组

 Array
(
    [0] => Array
        (
            [sexo_edad] => type1
            [fans] => 2
        )

    [1] => Array
        (
            [sexo_edad] => type2
            [fans] => 3
        )

    [2] => Array
        (
            [sexo_edad] => type1
            [fans] => 8
        )
    [3] => Array
        (
            [sexo_edad] => type2
            [fans] => 10
        )

)

如何根据typex键获取值的差以及如何如下所示显示数组

    Array
    (
        [0] => Array
            (
                [sexo_edad] => type1
                [fans] => 2
                [difference] => 0
            )
    [1] => Array
        (
            [sexo_edad] => type2
            [fans] => 3
            [difference] => 0
        )

    [2] => Array
        (
            [sexo_edad] => type1
            [fans] => 8
            [difference] => +6
        )
    [3] => Array
        (
            [sexo_edad] => type2
            [fans] => 10
           [difference] => +7
        )
)

请注意,分别将type1和type2值相减,并在关联数组的新值中获得差值

1 个答案:

答案 0 :(得分:1)

您可以遍历数组,检查以前是否看到过该类型的值,如果是,则取与最后一个值的差,否则将差设置为0。在两种情况下,我们都存储当前值用于将来的计算:

$type_values = array();
foreach ($array as &$arr) {
    if (isset($type_values[$arr['sexo_edad']])) {
        $arr['difference'] = $arr['fans'] - $type_values[$arr['sexo_edad']];
    }
    else {
        $arr['difference'] = 0;
    }
    $type_values[$arr['sexo_edad']] = $arr['fans'];
}
print_r($array);

输出:

Array ( 
    [0] => Array (
        [sexo_edad] => type1
        [fans] => 2
        [difference] => 0 
    )
    [1] => Array (
        [sexo_edad] => type2
        [fans] => 3
        [difference] => 0 
    )
    [2] => Array (
        [sexo_edad] => type1
        [fans] => 8
        [difference] => 6
    )
    [3] => Array (
        [sexo_edad] => type2
        [fans] => 10
        [difference] => 7
    ) 
)

Demo on 3v4l.org