I have this array:
$lista_agregados = array('po' => '0', 'brita' => '0');
And these arrays:
$po = array(0 => array('qt' => 12, 'total' => 1234),
1 => array('qt' => 45, 'total' => 13224));
$brita = array(0 => array('qt' => 54, 'total' => 124),
1 => array('qt' => 18, 'total' => 224));
I want to use a loop instead of explicit operations for every key in $lista_agregados:
$somatorio_mensal['po'] = $po[0]['total'] + $po[1]['total'];
$somatorio_mensal['brita'] = $brita[0]['total'] + $brita[1]['total'];
This is what I have so far:
foreach ($lista_agregados as $key => $value) {
$somatorio_mensal["'$key'"] = $key[0]['total'] + $key[1]['total'];
}
The problem is that $key[0] is interpreted as po[0] instead of $po[0].
Is there a way to make this work?
Try this:
foreach ($lista_agregados as $key => $value) {
$somatorio_mensal[$key] = ${$key}[0]['total'] + ${$key}[1]['total'];
}
Use a feature called variable variables:
foreach ($lista_agregados as $sub => $unused) {
// refer to variable called "$" + "$sub"
if (!isset(${$sub}))
continue;
$a = ${$sub};
if (! is_array($a))
continue;
$somatorio_mensal[$sub] = 0;
foreach ($a as $k => $v)
$somatorio_mensal[$sub] += $v['total'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With