2011-04-06 97 views
2

我想將一些值寫入多維數組,但只添加最後一個數組。這是我的代碼:使用foreach寫多維數組

 $test =array(); 
     foreach($key as $val): 
      $test = array('value1'=>$val->prop1,'value2' => $val->prop1); 
     endforeach; 

我的代碼中的錯誤在哪裏?

編輯:這應該在PHP中完成。

回答

5

你應該這樣做:

$test =array(); 
     foreach($key as $val): 
      $test[] = array('value1'=>$val->prop1,'value2' => $val->prop1); 
     endforeach; 

卷邊支架指示哪個位置插入,例如:

$test[2] = array('value1'=>$val->prop1,'value2' => $val->prop1); 

始終在第三位置插入(第三,因爲它開始於零)

在第一個例子中,當你使用空括號時,php在數組末尾添加新項目(追加)

2

我不知道用什麼語言,但我猜想,

$test = array('value1'=>$val->prop1,'value2' => $val->prop1); 

每一次都被分配一個新的數組。

1

使用$arr[]到新的價值附加到的$arr末:

$test = array(); 
foreach ($key as $val): 
    $test[] = array('value1' => $val->prop1, 'value2' => $val->prop1); 
endforeach;