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

后端 未结 3 1183
感情败类
感情败类 2021-01-29 00:45

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 wit

相关标签:
3条回答
  • 2021-01-29 01:04
        $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'];
    
    0 讨论(0)
  • 2021-01-29 01:08

    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;
              */
    
        }
        ?>
    
    0 讨论(0)
  • 2021-01-29 01:14

    I tend to like:

    $posts = array();
    while ($row = mysql_fetch_array($result)) {
        $posts[] = array(
             'id' => $row['id'],
             'title' => $row['title'],
             'text' => $row['text']
        );
    }
    
    0 讨论(0)
提交回复
热议问题