I want to create an array of associative arrays in a while loop. In each itteration of the while loop I want to add a new element in the array. How I can do that? After that I want to pass this array in a foreach and print the data. I have this part of code for now but obviously something is wrong with that.
while($row2 = mysql_fetch_array($result))
{
$myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
}
To add an element in the end of an array use []
Example:
$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
Obviously your access to $row2
looked wrong, so I assumed that here to be right
$myarray = array();
while($row2 = mysql_fetch_array($result)) {
// append something to your array with square brackets []
$myarray[] = array("id"=> $row2['id'], "name" => $row2['name'], "text"=>$row2['text']);
// or to maker this even shorter you could do
$myarray[] = $row2; // ... because it has the same array key names
}
Then later when you want to read from it:
foreach($myarray as $val) {
echo $val['name'].' (ID: '.$val['id'].') wrote following text: '.$val['text'];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With