6
   $total_materials_cost = 0;
   array_walk_recursive($materials, function($item, $key) {
        if (in_array($key, array('id'))) {

                    (....)

                    $total = $material_price * $material['amount'];

                    $total_materials_cost += $total;
                }
            }
        }
    });
echo $total_materials_cost;

对于上面的代码,我在 line 处收到错误$total_materials_cost += $total;,说变量未定义 - 我相信这是因为我在函数内部?但是我怎么能以任何方式绕过/解决这个问题,所以它确实添加到变量中?

4

1 回答 1

16

使用use关键字:

$total_materials_cost = 0;
array_walk_recursive($materials, function($item, $key) use(&$total_materials_cost) {
  if (in_array($key, array('id'))) {
    // (....)
    $total = $material_price * $material['amount'];
    $total_materials_cost += $total;
  }
});
echo $total_materials_cost;

传递引用 ( &) 以更改闭包外的变量。

于 2012-09-02T18:53:14.663 回答