For each result in a MySQL query, click on an array (complex)

Ok, thatโ€™s what I'm trying to do. I am using a MySQL query for recent posts. For each of the returned rows, I need to push the row identifier into the array, and then inside this identifier in the array I need to add more data from the rows. Multidimensional array.

Here is my code so far.

$query = "SELECT * FROM posts ORDER BY id DESC LIMIT 10"; $result = mysql_query($query); while($row = mysql_fetch_array($result)){ $id = $row["id"]; $post_title = $row["title"]; $post_text = $row["text"]; $post_tags = $row["tags"]; $post_category = $row["category"]; $post_date = $row["date"]; } 

As you can see, I have not done anything with arrays yet. Here is the ideal structure that I am looking for, just you can confuse.

The main array, I think you could name it. We will just call this array $ posts. Inside this array, I have one array for every row returned in my MySQL query. Inside these arrays there is $ post_title, $ post_text, etc.

How can I do it? I'm so confused. An example would be greatly appreciated.

-Dylan

0
source share
3 answers
  $master[$id]['post_title'] = $post_title; $master[$id]['post_text'] = $post_text; // etc 

or, less code. With this, you can get rid of where you set all these variables:

  $master[$row["id"]]['post_title'] = $row["title"]; $master[$row["id"]]['post_text'] = $row["text"]; // etc 

Edit in response to comment:

 foreach( $master as $row ) { echo $row['post_title']; } // or if you know the id echo $row[$id]['post_title']; 
+1
source

here you have a full reference to arrays, in any case, the general way to do this is to use $myarray[] = $aa; for push in it.

  <?php $query = "SELECT * FROM posts ORDER BY id DESC LIMIT 10"; $result = mysql_query($query); $posts = array(); while($row = mysql_fetch_array($result)){ $posts[] = $row; // second option, index the post by their id // $posts[$row["id"]] = $row; // third option /* $tmp = array(); $tmp["title"] = $row["title"]; $tmp["desc"] = $row["desc"]; $posts[$row["id"]] = $tmp; */ } ?> 
+1
source

I like:

 $posts = array(); while ($row = mysql_fetch_array($result)) { $posts[] = array( 'id' => $row['id'], 'title' => $row['title'], 'text' => $row['text'] ); } 
+1
source

All Articles