[英]Reduce Foreach Nesting and Replace With a While loop?
I've currently got a MySQL Script running in a while loop
which is as follows: 我目前有一个MySQL脚本在
while loop
运行,如下所示:
$Query = mysql_query("SELECT * FROM appointments");
while ($Rows = mysql_fetch_array($Query))
{
...
}
This returns a single row as an array and I can manipulate this as I want, for example: 这将返回一行作为数组,我可以根据需要进行操作,例如:
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']}'");
}
}
This will be placed within the while loop so I can work with the array itself. 这将放置在while循环中,因此我可以使用数组本身。 But I want to migrate over to PDO, and I'm having trouble with getting the
array
Format which I want: 但是我想迁移到PDO,并且在获取所需的
array
Format时遇到了麻烦:
Here is my code: 这是我的代码:
$Query = $dbh->prepare("SELECT * FROM appointments");
$Query->execute();
$Results = $Query->fetchAll();
print_r($Results);
This produces a multi-dimensional array which is as follows: 这将产生一个多维数组,如下所示:
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 )
)
What I am trying to do, is to have the $Results = $Query->fetchAll();
我想做的是让
$Results = $Query->fetchAll();
within a setup like the while loop
I used when using MySQL Functions. 在使用MySQL函数时使用的
while loop
之类的设置中。
If I want to get the Array Down To The single Strings I would have to do something like: 如果我想将数组简化为单个字符串,则必须执行以下操作:
foreach ($Results AS $results)
{
foreach ($results AS $result)
{
echo "{$result} <br>";
}
}
But This Returns: 但这返回:
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
Which has duplicate values. 其中具有重复的值。 My Questions is:
我的问题是:
1) Remove the duplicate Values 1)删除重复的值
2) Perform a while loop
while using my PDO Api -- But enable me to work with the Array keys as I am when I done the mysql_fetch_array
functions. 2)在使用我的PDO Api时执行
while loop
-但是使我能够像完成mysql_fetch_array
函数时一样使用Array键。
I believe you're looking for the options PDO::FETCH_ASSOC
to pass to fetchAll()
: 我相信您正在寻找要传递给
fetchAll()
的选项PDO::FETCH_ASSOC
:
$Query->fetchall(PDO::FETCH_ASSOC);
PDO::FETCH_ASSOC
gives you PDO::FETCH_ASSOC
给您
results = array(
[0] => array(
'column' => 'value',
'column' => 'value',
...
),
[1] => array(
...
},
...
);
Which you can then iterate over. 然后可以进行迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.