简体   繁体   中英

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:

$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. But I want to migrate over to PDO, and I'm having trouble with getting the array Format which I want:

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(); within a setup like the while loop I used when using MySQL Functions.

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

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.

I believe you're looking for the options PDO::FETCH_ASSOC to pass to fetchAll() :

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

PDO::FETCH_ASSOC gives you

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

Which you can then iterate over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM