Write multidemnensional array with foreach
I am trying to write some values into a multidimensional array, but only the last gets added. This is my code:
$test =array();
foreach($key as $val):
开发者_如何学运维 $test = array('value1'=>$val->prop1,'value2' => $val->prop1);
endforeach;
Where is the error in my code?
EDIT: This is shall be done in php.
You should do:
$test =array();
foreach($key as $val):
$test[] = array('value1'=>$val->prop1,'value2' => $val->prop1);
endforeach;
The curling brackets indicates which position to insert, for example:
$test[2] = array('value1'=>$val->prop1,'value2' => $val->prop1);
Always insert at third position (third because it starts at zero)
When you use empty brackets, as in the first example, php adds the new items at the end of the array (appends)
I don't know what language but I would guess that
$test = array('value1'=>$val->prop1,'value2' => $val->prop1);
Is allocating a new array every time.
Use $arr[]
to append your new value to the end of $arr
:
$test = array();
foreach ($key as $val):
$test[] = array('value1' => $val->prop1, 'value2' => $val->prop1);
endforeach;
精彩评论