PHP - PDO fetch resultset with column as index and column as value

假如想象 提交于 2020-01-23 11:41:34

问题


Hi i have a table with the following structure

+-------------+------+
| date        | price|
+-------------+------+
| 2014-02-19  |   34 |
| 2014-02-20  |   30 |
| 2014-02-21  |   28 |
+-------------+------+

At present PDO::FETCH_ASSOC returns an associative array with format like this

array(
  0=> array(
    "date" =>  2014-02-19 ,
    "price" => 34
),
 1=> array(
    "date" =>  2014-02-20 ,
    "price" => 30
),
 2=> array(
    "date" =>  2014-02-21 , 
    "price"=> 28
 )

)

This is alright by the way, but i was looking for a way to return the values as key => value pair with key is date and value is price. So that i can quickly access a price value using the date as the key and thus reduce the amount of computation by a lot, cause i have to deal with over several millions rows, and accessing each value in a loop is only causing the program to slow down much further.

So here is what i was looking for PDO::fetchALL() to return

array(
"2014-02-19" => 34,
"2014-02-20" => 30,
"2014-02-21" => 28
)

I mean i can easily build this using a foreach loop, but its not a possibility in my situation since its incurring huge performance drops. So if any one could point me in the right direction it would be really helpful. I will appreciate any sort of helps or tips.

Thanks, Maxx


回答1:


I don't think there's anything built-in that will do that. You can do it by using a normal fetch() loop:

$results = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $results[$row['date']] = $row['price'];
}



回答2:


I think it can be done with fetch options.

$sth = $dbh->prepare("SELECT date, price FROM some_table");
$sth->execute();


$sth->fetchAll(PDO::FETCH_KEY_PAIR|PDO::FETCH_GROUP);

It only works if the fetched data are a pair of values.




回答3:


Try foreach ($sql_stmt as $row)... Its easy to handle all your result sets...

Change the database name , user id , table name etc., according to your system

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbConnection= new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);

$sql_stmt = $dbConnection->prepare($sql_query="select date,price from table;");

$sql_stmt->execute();
foreach ($sql_stmt as $row) {
$date_col=$row['date']; 
$price_col=$row['price']; 
print $date_col;
print $price_col;
}

If you want to store value in array then use, like below in same foreach loop (declare and increment $i)

$date_col[$i]=$row['date']; 
$price_col[$i]=$row['price']; 


来源:https://stackoverflow.com/questions/21951145/php-pdo-fetch-resultset-with-column-as-index-and-column-as-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!