【问题标题】:How to grab MySQL data into a multidimensional array?如何将 MySQL 数据抓取到多维数组中?
【发布时间】:2010-07-16 00:22:44
【问题描述】:

如何使用 MySQL 数据形成多维数组?我现在正在使用这段代码:

while($row = mysql_fetch_assoc($result)){
    $music[$row['artist']][$row['title']][$row['id']][$row['category_id']] = $row['key'];
}

而且我认为使用多维数组来存储我的数据会容易得多(艺术家数组 => 标题数组 => id、category_id、key),但我不知道如何使用来自数据库。我google了一下,只能找到静态/本地数据多维数组的例子,这对我没有好处。

我也想知道如何在 php 中输出多维数据以供实际使用。我会使用循环吗?还是有别的办法?

我只想对我迄今为止在 stackoverflow 上获得的所有帮助表示感谢,它为我省去了很多麻烦!

【问题讨论】:

  • 请注意,每次都这样做可能有点昂贵。最好对代码进行结构化,以便对数据完成的所有工作都在循环内进行,而无需构造这个额外的数组。

标签: php mysql


【解决方案1】:
$music = array();
while($row = mysql_fetch_assoc($result)){
    if ( !isset($music[$row['artist']] ) {
        $music[$row['artist']] = array()
        }
    $music[$row['artist']][$row['title']]=array('id'=>$row['id'],'category_id'=>$row['category_id'],'key'=>$row['key'];
    }

或者更简单地说,如果内存需求不是非常重要(我主要这样做):

$music = array();
while($row = mysql_fetch_assoc($result)){
    if ( !isset($music[$row['artist']] ) {
        $music[$row['artist']] = array()
        }
    $music[$row['artist']][$row['title']]=$row;
    }

使用两个 for-as 循环会起作用——假设您想显示艺术家树,而不是标题的子树:

foreach ( $music as $artist => $titles ) {
    foreach ( $titles as $title => $details ) {
        // do stuff, $details contains all the details for the specific $artist and $title
        }
    }

【讨论】:

  • 非常感谢,这正是我想要的:)。
【解决方案2】:
var $music = array()
while($row = mysql_fetch_assoc($result))
{
    foreach($row as $k => $v)
    {
        $music[$key][] = $v;
    }
}

print_r($music);

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 2015-11-24
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多