如何在php中获取记录数组

时间:2017-04-02 14:43:15

标签: php mysql pdo

我用php执行SQL查询,这是代码:

$get_inspection_dates_query = "SELECT `date` 
                                            FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                                            WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);
$inspection_dates = $result_set->fetchAll(PDO::FETCH_NUM);

inspection_dates是:

Array
(
[0] => Array
    (
        [0] => 2012-01-01
    )

[1] => Array
    (
        [0] => 2013-01-01
    )

)

但我不想要这个。 我只想要一个没有列的记录数组(因为我只选择一列,所以我不需要在数组中有一个数组),如下所示:

Array
(
    [0] = 2012-01-01
    [1] = 2013-01-01
)

我知道我可以使用while循环和fetch$row = $result_set->fetch())达到类似的效果,但我认为这有点棘手。 有没有其他方法可以快速获得该数组?

3 个答案:

答案 0 :(得分:1)

尝试使用PDO::FETCH_COLUMN代替PDO::FETCH_NUM

$inspection_dates = $result_set->fetchAll(PDO::FETCH_COLUMN);

答案 1 :(得分:0)

只需一次获得一个结果,并将日期放在数组中,就像这样

$get_inspection_dates_query = "SELECT `date` 
                               FROM `vehicles` INNER JOIN `inspection_dates` ON `plate` = `id_vehicle`
                               WHERE `plate` = '$vehicle_plate'";
$result_set = $connection->query($get_inspection_dates_query);

$inspection_dates = array();  // init an empty array
while ( $row = $result_set->fetch(PDO::FETCH_NUM) ) {
    $inspection_dates[] = $row[0];
}

答案 2 :(得分:0)

要将inspection_dates更改为您想要使用的内容:

$whatYouWant = array_column($inspection_dates,0);