Джойны замедляют скорость работы запроса. Но сильно ли?
<?php
$datapost = array(
array(
'header' => 'город Москва',
'category_id' => '1',
),
array(
'header' => 'село Огонёво',
'category_id' => '2',
),
array(
'header' => 'село Быстрино',
'category_id' => '2',
),
array(
'header' => 'посёлок Восточный',
'category_id' => '7',
),
);
$query = mysqli_query($connect, "SELECT `id`, `title` FROM `category` ORDER BY `title`");
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
$arIDs = [];
foreach($rows as $row) {
$arIDs[$row['id']] = $row['title'];
}
$arResults = [];
foreach($datapost as $data) {
if(array_key_exists($data['category_id'], $arIDs)) {
$arResults[$data['category_id']]['title'] = $arIDs[$data['category_id']];
$arResults[$data['category_id']]['items'][] = $data;
}
}
$RESULT = [];
foreach($arIDs as $id => $title) {
if(array_key_exists($id, $arResults))
$RESULT[$id] = $arResults[$id];
else
$RESULT[$id] = [
'title' => $title,
'items' => [],
];
}
//print_r($RESULT);
foreach($RESULT as $result) {
$result['title'] // Название категории
foreach($result['items'] as $item) {
$item['header'] // Название подменю
}
}
<?php
$datapost = array(
array(
'header' => 'город Москва',
'category_id' => '1',
),
array(
'header' => 'село Огонёво',
'category_id' => '2',
),
array(
'header' => 'село Быстрино',
'category_id' => '2',
),
array(
'header' => 'посёлок Восточный',
'category_id' => '7',
),
);
$query = mysqli_query($connect, "SELECT `id`, `title` FROM `category` ");
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
$arIDs = [];
foreach($rows as $row) {
$arIDs[$row['id']] = $row['title'];
}
$arResults = [];
foreach($datapost as $data) {
if(array_key_exists($data['category_id'], $arIDs)) {
$arResults[$data['category_id']]['title'] = $arIDs[$data['category_id']];
$arResults[$data['category_id']]['items'][] = $data;
}
}
print_r($arResults);
???