Результат запроса и отображение на веб-странице (Nested Array) - PullRequest
0 голосов
/ 27 марта 2020
    {% for i in coupontesting %}
    <center>

        <div class="rectangle">
    <span class="right">Store Link</span><span class="left">{{ i.seller_store_name   }}</span>
    <div class="coupon-frame">
                        <div class="coupon-left-div coupon-align-center">
                            <div style="padding: 1.125rem;border-left: 1px solid #d4d4d4;">
                                <div style="position:relative;">
                                    <div class="coupon-left-img-div text-center coupon-align-center orange pt-32">
                    <span class="bold-18">{{ i.name }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="coupon-ticket-frame">
                                <div class="coupon-ticket-frame-style">
                                    <div class="oupon-ticket-frame-line"></div>
                                </div>
                            </div>
                        </div>
                        <div class="coupon-right-div coupon-align-center">
                {{ i.coupon_code }}
                        </div>

            <div class="coupon-right-div coupon-align-center">
                <button> Use Now </button>
            </div>
    </div>
    <br><br>
    </div>
    </center>
{% endfor %}

Над страницей просмотра

Ниже мой запрос со страницы модели

   $query = $this->db->query("SELECT * FROM coupon c INNER JOIN coupon_customer cc ON c.coupon_id = cc.coupon_id LEFT JOIN coupon_store cs ON c.coupon_id = cs.seller_store_id LEFT JOIN seller_store ss ON c.seller_store_id = ss.seller_store_id WHERE cc.customer_id = $customer_id AND c.date_end > NOW() ");

       if ($query->num_rows) {
            return $query->rows;
        } else {
            return 0;
        }

Структура таблицы

Table: coupon
 coupon_id(PK)   name   coupon_code  date_start   date_end  



Table: coupon_customer 
coupon_id(FK)    customer_id(FK)



Table: coupon_store
 coupon_store_id(PK)    coupon_id(FK)    seller_store_id(FK)



Table: seller_store
 seller_store_id(PK)    seller_store_name    seller_id(FK)

 Table: seller
 seller_id(FK)     seller_name   seller_email

 Table: customer
 customer_id(PK)    customer_name customer_email  

Все работает нормально, но я хотел спросить, есть ли в любом случае "группировка одного и того же продавца магазина?" Изображение: https://prnt.sc/rnjbbf (результат из моего кода)

Что я хотел: https://prnt.sc/rnjbqs

Если один и тот же магазин, он будет группироваться вместе, а не в новой строке, снова показывая название магазина

1 Ответ

0 голосов
/ 27 марта 2020

Предполагая, что набор результатов запроса выглядит следующим образом (для краткости я удалил большинство полей):

$rows = [
    ['seller_store_id' => 1, 'seller_store_name' => 'Foodlama', 'seller_id' => 11, 'coupon_id' => 6322],
    ['seller_store_id' => 2, 'seller_store_name' => 'BlueFood Market', 'seller_id' => 33, 'coupon_id' => 555],
    ['seller_store_id' => 2, 'seller_store_name' => 'BlueFood Market', 'seller_id' => 33, 'coupon_id' => 7787],
];

Затем можно переформатировать этот набор результатов, чтобы сгруппировать их по хранилищу:

$reformatted = [];
foreach ($rows as $row) {
    // here we get all the other key => value pairs that aren't used for grouping
    $nonStoreInfo = array_filter($row, function ($key) {
        return $key !== 'seller_store_id' && $key !== 'seller_store_name' && $key !== 'seller_id';
    }, ARRAY_FILTER_USE_KEY);
    /*
     * We have to manually add any data that is common for the group.
     *
     * Here we overwrite it with each iteration to avoid unnecessary conditional statements
     * (checking if the key exists and has a value). It's cleaner and more concise like this.
     * It doesn't matter because it is the same for every group anyway.
    */
    $reformatted[$row['seller_store_id']]['seller_store_name'] = $row['seller_store_name'];
    $reformatted[$row['seller_store_id']]['seller_id'] = $row['seller_id'];
    $reformatted[$row['seller_store_id']]['coupons'][] = $nonStoreInfo;
}

Обратите внимание, что я сделал предположение о seller_id. Если он может отличаться для любого seller_store_id, то вы должны удалить его из обратного вызова array_filter, а также удалить ручное присвоение $reformatted[$row['seller_store_id']]['seller_id'] = $row['seller_id'];. Аналогично, если вам нужно добавить что-то в группу, вам нужно добавить сравнение ключей в array_filter и добавить ручное назначение.

Это в конечном итоге выведет массив, подобный this:

Array (
    [1] => Array (
        [seller_store_name] => Foodlama
        [seller_id] => 11
        [coupons] => Array (
            [0] => Array (
                [coupon_id] => 6322
            )
        )
    )
    [2] => Array (
        [seller_store_name] => BlueFood Market
        [seller_id] => 33
        [coupons] => Array (
            [0] => Array (
                [coupon_id] => 555
            )
            [1] => Array (
                [coupon_id] => 7787
            )
        )
    )
)

Теперь в вашем шаблоне вы можете итерировать верхний уровень (магазины), а затем итерировать купоны внутри магазинов. Вы можете поэкспериментировать со структурой массива и точными данными, которые вам нужны в группе, чтобы соответствовать вашим потребностям.

...