Home > Back-end >  Array_Sum json/array
Array_Sum json/array

Time:03-06

i have a question about my code. so, i have a data like this :

Array
(
    [12x2060] => Array
        (
            [hashrate] => 12
            [sharesPerSecond] => 0.0188125
        )

    [6x3080ti] => Array
        (
            [hashrate] => 44
            [sharesPerSecond] => 0.0185625
        )

    [8x1660s] => Array
        (
            [hashrate] => 11
            [sharesPerSecond] => 0.00975
        )

)
Array
(
    [12x2060] => Array
        (
            [hashrate] => 5
            [sharesPerSecond] => 0.0188125
        )

    [6x3080ti] => Array
        (
            [hashrate] => 8
            [sharesPerSecond] => 0.0185625
        )

    [8x1660s] => Array
        (
            [hashrate] => 3
            [sharesPerSecond] => 0.00975
        )

)

and more the same data like historical statistic. i want to calculate [hashrate] become like this :

totalhashrate = 67
totalhashrate2 = 16

while the name like 12x2060,6x3080ti, are randomly depend to user data.
anyone please show me the code how to do it?

CodePudding user response:

You can use array_column and then array_sum that returned data.

$total = array_sum(array_column($array, 'hashrate'));

With your example data:

$array = [];
$array['12x2060']['hashrate'] = 12;
$array['12x2060']['sharesPerSecond'] =  0.0188125;
$array['6x3080ti']['hashrate'] = 44;
$array['6x3080ti']['sharesPerSecond'] => 0.0185625
$array['8x1660s']['hashrate'] => 11;
$array['8x1660s']['sharesPerSecond'] => 0.00975;

You can then do:

$totalHashRate = array_sum(array_column($array, 'hashrate'));

print $totalHashRate;
// Prints 67

CodePudding user response:

You could try something like below :

$arr1 = [
    '111' => [
        'hashrate' => 23
    ],
    '112' => [
        'hashrate' => 134
    ]
];
$arr2 = [
    '222' => [
        'hashrate' => 1
    ],
    '223' => [
        'hashrate' => 10
    ]
];

// From this
$hashrate1 = 0;
foreach ($arr1 as $key => $value) {
    $hashrate1  = $value['hashrate'];
}
$hashrate2 = 0;
foreach ($arr2 as $key => $value) {
    $hashrate2  = $value['hashrate'];
}
var_dump($hashrate1, $hashrate2);

And the result would be like this :

int(157) int(11)
  •  Tags:  
  • php
  • Related