Get value from specific key and value

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.

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;

No, it’s not from database.

Thans anyway.

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

i.e.

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

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

?>
1 Like

Thank you, it’s beautiful.

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

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

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