我目前在while loop
中运行了一个MySQL脚本,如下所示:
$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 )
)
我想要做的是在$Results = $Query->fetchAll();
设置中使用我在使用MySQL函数时使用的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
功能时,可以像我一样使用数组键。
答案 0 :(得分:0)
我相信您正在寻找传递给fetchAll()
的选项PDO::FETCH_ASSOC
:
$Query->fetchall(PDO::FETCH_ASSOC);
PDO::FETCH_ASSOC
为您提供
results = array(
[0] => array(
'column' => 'value',
'column' => 'value',
...
),
[1] => array(
...
},
...
);
然后你可以迭代。