Get value from specific key and value


#1

I have an array like this below:

Array
(
[0] => Array
    (
        [cat_id] => 1
        [user_id] => 14
        [value] => 3
    )

[1] => Array
    (
        [cat_id] => 2
        [user_id] => 14
        [value] => 4
    )

[2] => Array
    (
        [cat_id] => 3
        [user_id] => 14
        [value] => 3
    )

[3] => Array
    (
        [cat_id] => 1
        [user_id] => 15
        [value] => 4
    )

[4] => Array
    (
        [cat_id] => 2
        [user_id] => 15
        [value] => 4
    )

[5] => Array
    (
        [cat_id] => 3
        [user_id] => 15
        [value] => 4
    )

[6] => Array
    (
        [cat_id] => 1
        [user_id] => 1
        [value] => 4
    )

[7] => Array
    (
        [cat_id] => 2
        [user_id] => 1
        [value] => 4
    )

[8] => Array
    (
        [cat_id] => 3
        [user_id] => 1
        [value] => 3
    )

How do I the sum of key 'value' from the same value of key 'cat_id', for example I want to get sum from all key 'cat_id' = 1, where their values 3, 4, 4 which the sum would be 11.


#2

Where is this array data coming from? If it is from a Database, just query for the data you want.

SELECT SUM(value)
FROM your_table WHERE cat_id = 1;


#3

No, it's not from database.

Thans anyway.


#4

Couldn’t you have the PHP code do what the SELECT would do?

i.e.

$total = 0; 
if ($cat_id === 1) { 
  $total += $value; 
}

#7

Where does this array come from? How is it generated?

Try this:

<?
$a = array(
    array(
        "cat_id" => 1,
        "user_id" => 14,
        "value" => 30
    ),
    
    array(
        "cat_id" => 2,
        "user_id" => 14,
        "value" => 4
    ),
    
    array(
        "cat_id" => 3,
        "user_id" => 14,
        "value" => 3
    ),
    
    array(
        "cat_id" => 1,
        "user_id" => 15,
        "value" => 4
    ),
    
    array(
        "cat_id" => 2,
        "user_id" => 15,
        "value" => 4
    ),
    
    array(
        "cat_id" => 3,
        "user_id" => 15,
        "value" => 4
    ),
    
    array(
        "cat_id" => 1,
        "user_id" => 1,
        "value" => 4
    ),
    
    array(
        "cat_id" => 2,
        "user_id" => 1,
        "value" => 4
    ),
    
    array(
        "cat_id" => 3,
        "user_id" => 1,
        "value" => 3
    )
);


foreach ($a as $k => $v)
    {
    if ($v['cat_id'] == 1)
        {
        $t[] = $v['value'];
        }
    }

echo array_sum($t);

?>

#8

Thank you, it's beautiful.


#9

I still want to know where the array comes from. I doubt it is just a hard coded array.


#10

array_reduce() to an array of all values, then array_sum() it.


#11

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.