1

我目前正在运行一个 MySQL 脚本while loop,如下所示:

$Query = mysql_query("SELECT * FROM appointments");
    while ($Rows = mysql_fetch_array($Query))
    {
        ...
    }

这会将单行作为数组返回,我可以根据需要对其进行操作,例如:

if ($Rows['Reoccour'] == 1)
        {
            $NextDate = date('o-m-d', strtotime($Rows['Date'] . " +" . $Rows['howfar'] . " weeks"));
            if ($NextDate < date('o-m-d'))
            {
                mysql_query("UPDATE appointments SET Date='$NextDate' WHERE ID='{$Rows['ID']}'");
            }
        }

这将放置在 while 循环中,以便我可以使用数组本身。但我想迁移到 PDO,但我无法获得array我想要的格式:

这是我的代码:

$Query = $dbh->prepare("SELECT * FROM appointments");
    $Query->execute();
    $Results = $Query->fetchAll();
    print_r($Results);

这将产生一个多维数组,如下所示:

Array ( 
    [0] => Array ( 
    [ID] => 1 
    [0] => 1 
    [Appointment] => JCP Lucy
    [1] => JCP Lucy 
    [Date] => 2012-12-21
    [2] => 2012-12-21
    [Location] => Grays JCP
    [3] => Grays JCP 
    [Reoccour] => 1 
    [4] => 1 
    [howfar] => 1 
    [5] => 1
    )

    [1] => Array ( 
    [ID] => 3
    [0] => 3 
    [Appointment] => JCP Sign On
    [1] => JCP Sign On 
    [Date] => 2012-12-14 
    [2] => 2012-12-14 
    [Location] => 
    JCP Grays 
    [3] => JCP Grays 
    [Reoccour] => 1 
    [4] => 1 
    [howfar] => 2 
    [5] => 2 ) 

 ) 

我想要做的是在我使用 MySQL 函数时使用$Results = $Query->fetchAll();的设置中。while loop

如果我想将数组缩小到单个字符串,我将不得不执行以下操作:

foreach ($Results AS $results)
{
    foreach ($results AS $result)
    {
        echo "{$result} <br>"; 
    }
}

但这会返回:

1
JCP Lucy
JCP Lucy
2012-12-21
2012-12-21
Grays JCP
Grays JCP
1
1
1
1
3
3
JCP Sign On
JCP Sign On
2012-12-14
2012-12-14
JCP Grays
JCP Grays
1
1
2
2 

其中有重复的值。我的问题是:

1)删除重复的值

2) 使用我的 PDO Api 执行一段while loop时间——但让我能够像我在完成这些mysql_fetch_array功能时一样使用 Array 键。

4

1 回答 1

0

我相信您正在寻找PDO::FETCH_ASSOC传递给的选项fetchAll()

$Query->fetchall(PDO::FETCH_ASSOC);

PDO::FETCH_ASSOC给你

results = array(
  [0] => array(
    'column' => 'value',
    'column' => 'value',
    ...
  ),
  [1] => array(
     ...
  },
  ...
);

然后您可以对其进行迭代。

于 2012-12-21T15:54:12.683 回答