array_splice
array array_splice ( array
&$input
, int $offset
[, int $length
= count($input)
[, mixed $replacement
= array()
]] ) 當參數 3 為 0 時, 表示不置換原陣列中的任一元素, 而是在參數 2 指定的位置後插入新元素。
// 原陣列 $rs = array(array("name" => "johnber", "money" => 100), array("name" => "ann", "money" => 10), array("name" => "catherine", "money" => 50), array("name" => "andrew", "money" => 300) ); print_r($rs); echo '<br /><br />'; $nowpos = 1; $submoney = 0; $totalmoney = 0; foreach($rs as $key => $val) { $submoney += $val['money']; $totalmoney += $val['money']; if($val['name']=='ann') { // 當遇到 name= ann 的陣列元素時, 插入新的陣列元素 $insert = array(array("name" => "subtotal", "money" => $submoney)); array_splice($rs, $nowpos, 0, $insert); $submoney = 0; } $nowpos++; } array_push($rs, array("name" => "total", "money" => $totalmoney)); print_r($rs); echo '<br /><br />'; echo 'submoney = '.$submoney.'<br /><br />'; echo 'totalmoney = '.$totalmoney.'<br /><br />';