如何为我的播放列表创建多维数组?

时间:2011-04-26 05:57:11

标签: php mysql

我想为歌词网站创建一个播放列表部分。

对于创建跟踪列表,多维数组是最好的输入方式吗?我的MD阵列中有两个输入是歌曲,另一个是与之对应的艺术家。我可以使用JS动态创建一个文本框。请帮我创建MD阵列并使用循环在Db中输入。请提供基本的想法以及我稍后会修改的代码。

    Tracks    |    Artist
    _____________________

    A         |    ar1
    B         |    ar2
    C         |    ar3

想要将这种类型的输入填充到DB。

2 个答案:

答案 0 :(得分:0)

PHP没有多维数组,但嵌套数组。他们模拟尺寸。还有一些对象可以保存数据集。所以你必须使用数组或对象=)

您可以在阵列中以多种形式获取数据。例如。

$myarray = array(0=>array('artist'=>'someone','tracks'=>array(tracks...)),
                 1=>array(...));

答案 1 :(得分:0)

这是一个基本类,可用于将数据库返回的结果用作对象数组。

    <?php
/*
 * Default database class, stores connections and queries
 * and all does db interaction
 */
class Database {

    private static $connection;
    private static $current_query;


    function __construct() {
        // do something
    }

    public static function open_connection() {
        $db_server = 'localhost';
        $db_user = 'db_user';
        $db_pass = 'db_pass';
        $db_name = 'db_name';
        $connection = mysql_connect($db_server,$db_user,$db_pass);
        if (!$connection){
            // throw error
            die ("Connection to database failed: ". mysql_error() ." $db_server,$db_user,$db_pass"); // debug
        }

        $db_select = mysql_select_db($db_name,$connection);
        if (!$db_select){
            // throw some error
            //die("Database selection Failed: " .mysql_error());
        }
        self::$connection = $connection;
    }

    public static function close_connection() {
        if (isset(self::$connection)){
            mysql_close(self::$connection);
            unset(self::$connection);
        }
    }

    public function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        try {
            $result = mysql_query($sql,self::$connection);
        } catch (Exception $e) {
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
        }
        return $result;
    }


    private static function instantiate($record) {
        $obj = new self;
        foreach ($record as $k =>$value){
            $obj->$k = $value;
        }
        return $obj;
    }

    public static function find_by_sql($sql){
        if (!is_string($sql))
        return false;
        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }

}

现在可以访问您的数据

$playlist = Database::find_by_sql("SELECT * FROM `playlist`");

// loop through your result
foreach($playlist as $play){
   echo "<p>$play->tracks : $play->artist</p>";
}

这使您更容易与结果集交互,也许您应该研究find_by_sql()和instantiate()方法 古德勒克:)