Предполагая, что набор результатов запроса выглядит следующим образом (для краткости я удалил большинство полей):
$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
)
)
)
)
Теперь в вашем шаблоне вы можете итерировать верхний уровень (магазины), а затем итерировать купоны внутри магазинов. Вы можете поэкспериментировать со структурой массива и точными данными, которые вам нужны в группе, чтобы соответствовать вашим потребностям.