对于MySQL查询中的每个结果,推送到数组(复杂)

时间:2010-06-15 18:20:27

标签: php mysql arrays string multidimensional-array

好的,这就是我想要做的。我正在为最近的帖子运行MySQL查询。对于每个返回的行,我需要将行的ID推送到数组,然后在数组中的该ID内,我需要从行中添加更多数据。一个多维数组。

到目前为止,这是我的代码。

$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"];



}

正如您所看到的,我还没有对阵列做过任何事情。这是我正在寻找的理想结构,只是让你感到困惑。

我猜你可以称之为主阵列。我们只需将此数组称为$ posts。 在这个数组中,我在MySQL查询中返回的每一行都有一个数组。 在这些数组中有$ post_title,$ post_text等。

我该怎么做?我很困惑......一个例子会非常感激。

-Dylan

3 个答案:

答案 0 :(得分:1)

here您拥有数组的完整参考,无论如何,执行此操作的常用方法是使用$myarray[] = $aa;“推入”数组。

    <?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 :(得分:1)

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

或更少的代码。有了这个,您可以摆脱设置所有变量的位置:

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

编辑回答评论:

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

// or if you know the id

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

答案 2 :(得分:1)

我倾向于:

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