我正在查询我的 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_ridden作为值来制作我的 $dates 数组。
目前我正在执行以下操作(这不是我想做的):
while( $date = pg_fetch_row($theDates) ){
$dates[]['value'] = $date[1]; //date id is value
$dates[]['label'] = $date[0]; //date (in text form) is the label
}
我觉得这应该是一件非常简单的事情,但由于某种原因无法弄清楚。
我相信
您正在寻找的循环结构是:
while( $date = pg_fetch_row($theDates) ){
$dates[$date[1]] = $date[0];
}
如果我误解了,那么您当前尝试的问题在于它将 id 和标签作为单独的数组索引附加到 $dates
中。
相反,请尝试以下操作:
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["某些ID"],那么
while( $date = pg_fetch_row( $theDates ) ) {
$dates[$date[1]] = $date[0];
}