SQLite查询返回两次值

时间:2018-04-19 19:13:26

标签: php sqlite foreach

SQL表包含:

names:  id | firstName | lastName
phones: id | phone1    | phone2   | phone3

任务是显示注册用户的第一个&姓氏。然后,根据用户的ID,显示电话号码(如果存在)。另外,我需要有机会扩展'手机'表,所以我不能只使用字符串连接,因为我不知道数字的数量。

恕我直言,它可以用foreach循环解决:

$stmt = $connection->prepare( 'SELECT firstName, lastName, id FROM names');
$stmt->execute();
foreach($stmt as $row)
{

    $stmt = $connection->prepare( 'SELECT phone1, phone2, phone3 FROM phones WHERE id=?');
    $stmt->execute([$row['id']]);
    $number_str = '';

    foreach($stmt as $numbers)  // for each user's array of phones
    {
        foreach($numbers as $number) {  // for each phone in the array
            if($number) {
                $number_str .= $number . ', ';  // build a string "phone1, phone2, phone3"
            }
        }
    }
    array_push($users, new User($row['firstName'], $row['lastName'], substr($number_str, 0, -2)));  // filling the array

不幸的是,每个用户的number_str看起来像:phone1,phone1,phone2,phone2等。

更新

$stmt = $connection->prepare( 'SELECT firstName, lastName, id FROM names');
$stmt->execute();
foreach($stmt as $row) {

    $stmt1 = $connection->prepare('SELECT phone1, phone2, phone3 FROM phones WHERE id=?');
    $stmt1->execute([$row['id']]);
    $a = $stmt1->fetch();

    $number_str = $a[0].$a[1].$a[2]; // phone1phone2phone3  -- works FINE, but why? btw, count($a) is 6, but I can't access $a[3]
    $number_str = implode(', ', $a); // phone1, phone1, etc

    array_push($users, new User($row['firstName'], $row['lastName'], $number_str));  // filling the array
}

1 个答案:

答案 0 :(得分:0)

我非常确定您需要获取结果,然后您将收到预期的结果。

> library(ncdf4)
> rm(list=ls())
> fn <- "D:/logiciel/KHAMES/OISST_HR_NRT-GOS-L4-MED-v2.0.nc"
> cdf<- nc_open(fn)
> nc
lat <- ncdf4::ncvar_get(cdf, varid="lat")
lon <- ncdf4::ncvar_get(cdf, varid="lon")
time <- ncdf4::ncvar_get(cdf, varid="time")
sst <- ncdf4::ncvar_get(cdf, varid="analysed_sst")
time_d <- as.Date(time, format="%j", origin=as.Date("1981-01-01"))
time_years <- format(time_d, "%Y")
time_months <- format(time_d, "%m")
time_year_months <- format(time_d, "%Y-%