For each result in MySQL query, push to array (complicated)

纵饮孤独 提交于 2019-12-31 06:47:07

问题


Okay, here's what I'm trying to do. I am running a MySQL query for the most recent posts. For each of the returned rows, I need to push the ID of the row to an array, then within that ID in the array, I need to add more data from the rows. A multi-dimensional array.

Here's my code thus 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 haven't done anything with arrays yet. Here's an ideal structure I'm looking for, just incase you're confused.

The master array I guess you could call it. We'll just call this array $posts. Within this array, I have one array for each row returned in my MySQL query. Within those arrays there is the $post_title, $post_text, etc.

How do I do this? I'm so confused.. an example would be really appreciated.

-Dylan


回答1:


    $master[$id]['post_title'] = $post_title;
    $master[$id]['post_text'] = $post_text;
    // etc

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

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

Edit in answer to comment:

foreach( $master as $row )
{
    echo $row['post_title'];
}

// or if you know the id

echo $row[$id]['post_title'];



回答2:


here you have the complete reference for arrays, anyway a common way to do this is to use $myarray[] = $aa; to "push" into 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;
          */

    }
    ?>



回答3:


I tend to like:

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


来源:https://stackoverflow.com/questions/3047896/for-each-result-in-mysql-query-push-to-array-complicated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!