w4r0
November 5, 2017, 2:51pm
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.
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;
w4r0
November 5, 2017, 4:53pm
3
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
w4r0
November 6, 2017, 2:01am
8
benanamen:
<?
$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);
?>
Thank you, itās beautiful.
I still want to know where the array comes from. I doubt it is just a hard coded array.
chorn
November 6, 2017, 6:58am
10
array_reduce()
to an array of all values, then array_sum()
it.
system
Closed
February 5, 2018, 1:58pm
11
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.