在PHP的foreach循环中插入一个$ key作为变量

时间:2016-11-02 16:48:04

标签: php foreach

我有这个数组:

$lista_agregados = array('po' => '0', 'brita' => '0');  

这些数组:

$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));  

我想对$lista_agregados中的每个键使用循环而不是显式操作:

$somatorio_mensal['po'] = $po[0]['total'] + $po[1]['total'];
$somatorio_mensal['brita'] = $brita[0]['total'] + $brita[1]['total'];

这是我到目前为止所做的:

foreach ($lista_agregados as $key => $value) {
    $somatorio_mensal["'$key'"] = $key[0]['total'] + $key[1]['total'];
}  

问题是$key[0]被解释为po[0]而不是$po[0]。 有没有办法使这项工作?

3 个答案:

答案 0 :(得分:3)

试试这个:

foreach ($lista_agregados as $key => $value) {
    $somatorio_mensal[$key] = ${$key}[0]['total'] + ${$key}[1]['total'];
} 

答案 1 :(得分:3)

使用名为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'];
}

答案 2 :(得分:2)

警告您有brita1作为其中一个键,但变量名为brita。修复后,您可以这样做:

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