Create an array of associative arrays in PHP

I want to create an array of associative arrays in a while loop. In each iteration of the while loop, I want to add a new element to the array. How can i do this? After that, I want to pass this array to foreach and print the data. At the moment I have this part of the code, but obviously something is wrong with this.

while($row2 = mysql_fetch_array($result)) { $myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]); } 
+7
source share
4 answers

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

 $myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]); 
+16
source

Obviously, well, first select it to find out something:

 while($row2 = mysql_fetch_array($result)) { ... } 

This part looks good, let it look inside the loop:

 $myarray = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]); 

There are several points. Probably the most important thing, since inside the loop you overwrite $myarray at each iteration. Instead, you want to add to the array. Let me do this:

 $myarray = array(); # initialize the array first! while($row2 = mysql_fetch_array($result)) { $myarray[] = $row2; # add the row } 

After that, you can bring it out to prove that it basically works:

 var_dump($myarray); 

This shows you an array containing all the rows. Then you only need to modify the database query so that it returns fields that are of interest to you.

If you cannot do this with the database, you can also manipulate the array:

 $myarray = array(); # initialize the array first! while($row2 = mysql_fetch_array($result)) { $myarray[] = array( "id" => $theid, "name" => name($id), "text" => $row2['text'] ); } var_dump($myarray); 

Now the result should look the way you want. To output $myarray :

 foreach ($myarray as $number => $row) { echo '<div>Number ', $number, ':<dl>'; foreach ($row as $k => $v) { printf("<dt>%s</dt><dd>%s</dd>\n", $k, htmlspecialchars($v)); } echo '</dl></div>' } 
+6
source

If you are trying to add to $ myarray at each iteration, do the following:

 $myarray[] = array("id"=>$theid, "name"=>name($id), "text"=>$row2[text]); 

or like this:

 array_push($myarray, array("id"=>$theid, "name"=>name($id), "text"=>$row2[text])); 
+3
source

Obviously your access to $row2 didn’t look right, so I assumed that it would be correct here

 $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']; } 
+1
source