Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

foreach

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?

like image 208
Luís Alves Avatar asked Dec 10 '25 19:12

Luís Alves


2 Answers

Try this:

foreach ($lista_agregados as $key => $value) {
    $somatorio_mensal[$key] = ${$key}[0]['total'] + ${$key}[1]['total'];
} 
like image 177
Armin Sam Avatar answered Dec 12 '25 10:12

Armin Sam


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'];
}
like image 21
Ruslan Osmanov Avatar answered Dec 12 '25 11:12

Ruslan Osmanov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!