如何从查询中获取数组

时间:2014-08-20 20:56:40

标签: php

我有一个函数getCart,它有一个合并在一起的复杂查询。我想只选择一个$ cart的数组[' tee_times'] = array();并将该数组放在另一个函数中。我怎么能做到这一点?

以下是我试图提取的查询摘录。

function getCart($id, DBConnection $connection) {
$query    = 'SELECT * FROM cart WHERE IDCart=:cart_id LIMIT 1';
$prepared = array(
    "cart_id" => $id
);
$results  = $connection->fetch($query, $prepared);
$cart     = !empty($results) ? $results[0] : null;
if (isset($cart)) {
    $cart['IDCustomer']    = isset($cart['IDCustomer']) ? (int)$cart['IDCustomer'] :   null;
    $cart['IDDestination'] = isset($cart['IDDestination']) ?    (int)$cart['IDDestination'] : null;
    $cart['total']         = 0;
    $cart['tee_times']     = array();
    $cart['rooms']         = array();
    $cart['cars']          = array();
    $query                 = '
SELECT
a.*,
e. city_name,
f.IDDestination,
((CASE DATE_FORMAT(a.teetime_dt, "%w")
    WHEN 0 THEN b.sun
    WHEN 1 THEN b.mon
    WHEN 2 THEN b.tue
    WHEN 3 THEN b.wed
    WHEN 4 THEN b.thu
    WHEN 5 THEN b.fri
    WHEN 6 THEN b.sat
    ELSE 0
END) * a.no_rounds * a.no_golfers) price,
c.tax_rate
FROM cart_course_teetimes a
JOIN course_priceplan b
    ON b.IDCoursePricePlan = a.IDCoursePricePlan
JOIN course_tax c
    ON c.IDCourseTax = a.IDCourseTax
JOIN course d
    ON d.IDCourse = b. IDCourse
JOIN vw_cities e
    ON e.IDCity = d. IDCity
JOIN destinations_cities f
    ON f.IDCity = e.IDCity
WHERE IDCart=:cart_id
';
    $results               = $connection->fetch($query, $prepared);
    foreach ($results as $row) {
        $formatted           = array(
            'IDCartTeetimes'    => (int)$row['IDCartTeetimes'],
            'IDCoursePricePlan' => (int)$row['IDCoursePricePlan'],
            'IDCourseTax'       => (int)$row['IDCourseTax'],
            'teetime_date'      => $row['teetime_dt'],
            'num_golfers'       => (int)$row['no_golfers'],
            'num_rounds'        => (int)$row['no_rounds'],
            'price'             => (float)$row['price'],
            'tax_rate'          => (float)$row['tax_rate'],
            'city_name'         => $row['city_name'],
            'IDDestination'     => (int)$row['IDDestination'],
        );
        $cart['tee_times'][] = $formatted;
        $cart['total'] += $formatted['price'];

    }

这是我的功能和我尝试检索tee_times数组

function filterCart($cart_id, DBConnection $connection) {
$cart = getCart($cart_id, $connection);
if (!isset($cart)) {
    http_response_code(404);
    return 'Cart does not exist.';
}
$results =$cart['tee_times'];
echo $results;
$id = null;
foreach ($results as $row){
    var_dump($row['IDDestination']);

1 个答案:

答案 0 :(得分:0)

如果您要过滤掉多个IDDestination的课程,请将WHERE子句更改为:

WHERE IDCart = :cart_id
AND IDCart NOT IN (
    SELECT IDCart
    FROM course a
    JOIN destinations_cities b ON b.IDCity = a.IDCity
    GROUP BY IDCart
    HAVING COUNT(*) > 1)