1

也许我早就习惯了使用 ORM 方法从数据库中提取数据,但我现在正在为我的一个朋友做一个简单的小项目,他不需要所有额外的 MVC、ORM 等等。 . 下面是我在 PHP 中构建的一个类中的查询示例。

$this->sqlstart();
$sql = "select label, setting from ".$this->_settings." where id <= 4";
$query = mysql_query($sql);

$result = array();
while($row = mysql_fetch_array($query))
{
    $result[] = $row;
}
return $result;

的输出return $result是:

Array
(
    [0] => Array
        (
            [0] => Week 1 Pay
            [label] => Week 1 Pay
            [1] => 2995
            [setting] => 2995
        )

    [1] => Array
        (
            [0] => Week 2 Pay
            [label] => Week 2 Pay
            [1] => 2995
            [setting] => 2995
        )

    [2] => Array
        (
            [0] => Week 1 Dates
            [label] => Week 1 Dates
            [1] => 1-15
            [setting] => 1-15
        )

    [3] => Array
        (
            [0] => Week 2 Dates
            [label] => Week 2 Dates
            [1] => 16-31
            [setting] => 16-31
        )

)

它应该是

Array
(
    [0] => Array
        (
            [label] => Week 1 Pay
            [setting] => 2995
        )

    [1] => Array
        (
            [label] => Week 2 Pay
            [setting] => 2995
        )

    [2] => Array
        (
            [label] => Week 1 Dates
            [setting] => 1-15
        )

    [3] => Array
        (
            [label] => Week 2 Dates
            [setting] => 16-31
        )

)

谁能向我指出集合中的其他数据来自哪里?

4

4 回答 4

5

您应该使用mysql_fetch_assoc正确获得结果。它将为您提供一个关联数组而不是普通数组。

于 2013-03-30T23:18:04.983 回答
2

来自http://php.net/manual/en/function.mysql-fetch-array.php

array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )

要么MYSQL_ASSOC作为第二个参数传递以获取关联数组,要么只调用mysql_fetch_assoc().

于 2013-03-30T23:16:40.967 回答
2

您应该能够传入第二个参数,它只会输出关联的列名:

while($row = mysql_fetch_array($query, MYSQL_ASSOC))
于 2013-03-30T23:16:42.777 回答
0

mysql_fetch_array返回两种访问值的方式:字段名索引号。您可以将代码更改mysql_fetch_arraymysql_fetch_assoc或更改为:

while($row = mysql_fetch_array($query)){
     $result[] = array('label' => $row['label'], 'setting' => $row['setting'];
 }
于 2013-03-30T23:20:40.363 回答