【问题标题】:For each result in MySQL query, push to array (complicated)对于 MySQL 查询中的每个结果,推送到数组(复杂)
【发布时间】:2011-03-04 03:17:57
【问题描述】:

好的,这就是我想要做的。我正在为最近的帖子运行 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 等。

我该怎么做?我很困惑.. 一个例子将不胜感激。

-迪伦

【问题讨论】:

    标签: php mysql arrays string multidimensional-array


    【解决方案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'];
    

    【讨论】:

    • 好的,谢谢。现在我正在尝试检索我的数据。对于每个帖子或 ID,我如何从数组中获取 post_title?
    • 不用担心。很高兴我们能提供帮助。
    【解决方案2】:

    我喜欢:

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

    【讨论】:

    • K.. 现在我有了数组,如何从主数组中的每个数组中检索 post_title 或文本?
    【解决方案3】:

    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;
              */
    
        }
        ?>
    

    【讨论】:

    • 我喜欢这种方式。它又好又干净。唯一的问题是,如果 OP 不希望数组中的每个字段都来自结果,只需要选择几个。
    • 是的,这就是我添加其他选项的原因
    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多