Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create array of associative arrays in PHP

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]);
                            }
like image 210
anna Avatar asked Apr 18 '12 21:04

anna


2 Answers

To add an element in the end of an array use []
Example:

$myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]);
like image 106
laltin Avatar answered Sep 30 '22 12:09

laltin


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'];
}
like image 22
dan-lee Avatar answered Sep 30 '22 12:09

dan-lee