Luís Alves Luís Alves - 1 month ago 8
PHP Question

Insert a $key as an variable in a foreach loop in PHP

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?

Answer

Be warned that you have brita1 as one of your keys, but the variable is called brita. With that fixed, you can do it like this:

foreach($lista_agregados as $key => $total) {
    foreach($$key as $k) {
        $lista_agregados[$key] += $k['total'];
    }
}
Comments