prepare($sql); $docStmt->execute($params); $documents = $docStmt->fetchAll(); $filesStmt = $pdo->prepare('SELECT * FROM doc_storage WHERE owner_id = ?'); $filesStmt->execute([$ownerId]); $filesByDoc = []; foreach ($filesStmt->fetchAll() as $f) { $filesByDoc[(int) $f['document_id']][] = present_file($f); } $result = array_map(function ($d) use ($filesByDoc) { $tpl = present_document_template($d); $tpl['files'] = $filesByDoc[(int) $d['document_id']] ?? []; return $tpl; }, $documents); json_data($result);