在PHP中向数组添加元素

时间:2014-04-13 12:59:56

标签: php silex

我使用Silex Framework,我想在计算年龄后将$ age添加到$ result 那可能吗?

$result = $app['db']->fetchAll($sql);

 foreach ($result as $DN) {
    $DT = $DN['dateN'];
        $am = explode('-', $DT);
        $an = explode('/', date('Y/m/d'));
        $age = $an[0] - $am[0];
        echo $age;
  }

 return $app['twig']->render('page.html',array('list' => $result,'age'=>$age));

2 个答案:

答案 0 :(得分:2)

您可以尝试使用引用(使用&)代替副本并添加项目:

foreach ($result as &$DN) {
    $DT = $DN['dateN'];
    $am = explode('-', $DT);
    $an = explode('/', date('Y/m/d'));
    $age = $an[0] - $am[0];
    $DN['age'] = $age;
}

答案 1 :(得分:0)

假设你的fetchAll返回一个数组数组"引用"你的结果集

foreach($result as $index => $row) {
    // ....
    $result[$index] = $age;
}