Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用postres获取id和name,创建以key作为id、value作为name的php数组_Php_Database_Arrays_Postgresql - Fatal编程技术网

使用postres获取id和name,创建以key作为id、value作为name的php数组

使用postres获取id和name,创建以key作为id、value作为name的php数组,php,database,arrays,postgresql,Php,Database,Arrays,Postgresql,我正在查询我的postgres数据库并获得一个名称和id,如下所示: $datesQuery = "SELECT date_ridden, id from dates WHERE user_id=$userId"; //query $theDates = pg_query($db, $datesQuery); //execute query $dates=array(); //want to use this array to have the key as id and value as da

我正在查询我的postgres数据库并获得一个名称和id,如下所示:

$datesQuery = "SELECT date_ridden, id from dates WHERE user_id=$userId"; //query
$theDates = pg_query($db, $datesQuery); //execute query
$dates=array(); //want to use this array to have the key as id and value as date_ridden
我想用id作为键,date_rided作为值来创建$dates数组

目前我正在做以下工作(这不是我想做的):


我觉得这应该是一件非常简单的事情,但由于某些原因,我无法理解。

我相信您正在寻找的循环结构是:

while( $date = pg_fetch_row($theDates) ){
    $dates[$date[1]] = $date[0];
}
如果我误解了,那么您当前尝试的问题是,它在
$dates
中附加id和标签作为单独的数组索引

相反,请尝试以下方法:

while( $date = pg_fetch_row($theDates) ){
    $dates[] = array('value' => $date[1],
                     'label' => $date[0]);
}
在本例中,您将访问一个条目,如
Value=$dates[0]['Value'],Label=$dates[0]['Label']]


希望其中一个能帮上忙。

如果我理解你的要求,那就是这样

while( $date = pg_fetch_row( $theDates ) ) {
    $dates[][$date[1]] = $date[0];
}
或者如果你想访问$dates['some id'],那么

while( $date = pg_fetch_row( $theDates ) ) {
    $dates[$date[1]] = $date[0];
}
while( $date = pg_fetch_row( $theDates ) ) {
    $dates[$date[1]] = $date[0];
}