Mario Gonzales Flores
Mario Gonzales Flores

Reputation: 705

Obtain the difference of values in an associative array

I have this array

 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
        )

)

How to obtain the difference of values according to the typex key and that the array should appear as shown below

    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
        )
)

Note that the type1 and type2 values are subtracted separately and the difference is obtained in a new value of the associative array called difference

Upvotes: 0

Views: 29

Answers (1)

Nick
Nick

Reputation: 147206

You can loop through the array, checking to see if you have seen a value of this type before, and if so taking the difference with the last value, otherwise setting the difference to 0. In both cases we store the current value for future calculations:

$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);

Output:

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

Upvotes: 1

Related Questions