Home > Blockchain >  How to get total amount from foreach lop in Laravel Controller
How to get total amount from foreach lop in Laravel Controller

Time:09-23

I want to get total amount from foreach lop data in the controller, for example, code bellow.


    $set = settings::findOrFail(1);
    $api = new \Binance\API("$set->api_key","$set->scrt_key");
    $api->useServerTime();

    $forusdvaluetotal = coins::whereuser_id(Auth::user()->id)->get();

    foreach($forusdvaluetotal as $coins){
        $getsymbol = $coins->symbol.'USDT';
        $getprice = $api->price("$getsymbol");
        $valueinusd = $coins->balance*$getprice;
        $total = $valueinusd;    
    }

    $gettotal = $total->sum();

like "coins A" price is $50 per coin and balance 2, "coins B" price is $50 per coin and balance 5, "coins C" price is $50 per coin and balance 1. So I want to get total amount in USD by balance like ('coins A' $502 = $100 'coins B' $505 = $250 'coins A' $50*1 = $50) = $400

Please help me how to solve that in laravel controller.

CodePudding user response:

Try this:

$total = 0;
foreach($forusdvaluetotal as $coins){
    $getprice = $coins['market_price'];
    $valueinusd = $coins['balance']*$getprice;
    $total  = $valueinusd;    
}

return $total;

CodePudding user response:

One elegant option would be to make use of Laravel's support collection method reduce().

The reduce method reduces the collection to a single value, passing the result of each iteration into the subsequent iteration:

The value for $carry on the first iteration is null; however, you may specify its initial value by passing a second argument to reduce:


$collection = coins::whereuser_id(Auth::user()->id)->get();

$total = $collection->reduce(function ($carry, $item) {
    return $carry   (floatval($item->balance) * floatval($item->market_price));
}, 0);

Addendum

Alternatively, you may make use of Laravel's support collection method sum().

The sum method returns the sum of all items in the collection:

In addition, you may pass your own closure to determine which values of the collection to sum:


$collection = coins::whereuser_id(Auth::user()->id)->get();

$total = $collection->sum(function ($item) {
    return (floatval($item->balance) * floatval($item->market_price));
});

Edit:

In response to your new question changes, you could solve it this way.

$set = settings::findOrFail(1);
$api = new \Binance\API("$set->api_key","$set->scrt_key");
$api->useServerTime();
$query = coins::whereuser_id(Auth::user()->id);

// Get symbols.
$symbols = $query->distinct('symbol')->pluck('symbol')->flip()->toArray();

// Fetch prices.
array_walk($symbols, function (&$value, $key) use ($api) {
    $value = $api->price("{$key}USDT");
});

// Get total sum.
$total = $query->get()->sum(function ($item) use ($symbols) {
    return (floatval($item->balance) * floatval($symbols[$item->symbol]));
});

  • Related